(self["webpackChunkqualibrate_frontend_ui"] = self["webpackChunkqualibrate_frontend_ui"] || []).push([[96],{

/***/ 41:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Rk: function() { return /* binding */ getRegisteredStyles; },
/* harmony export */   SF: function() { return /* binding */ registerStyles; },
/* harmony export */   sk: function() { return /* binding */ insertStyles; }
/* harmony export */ });
var isBrowser = true;

function getRegisteredStyles(registered, registeredStyles, classNames) {
  var rawClassName = '';
  classNames.split(' ').forEach(function (className) {
    if (registered[className] !== undefined) {
      registeredStyles.push(registered[className] + ";");
    } else if (className) {
      rawClassName += className + " ";
    }
  });
  return rawClassName;
}
var registerStyles = function registerStyles(cache, serialized, isStringTag) {
  var className = cache.key + "-" + serialized.name;

  if ( // we only need to add the styles to the registered cache if the
  // class name could be used further down
  // the tree but if it's a string tag, we know it won't
  // so we don't have to add it to registered cache.
  // this improves memory usage since we can avoid storing the whole style string
  (isStringTag === false || // we need to always store it if we're in compat mode and
  // in node since emotion-server relies on whether a style is in
  // the registered cache to know whether a style is global or not
  // also, note that this check will be dead code eliminated in the browser
  isBrowser === false ) && cache.registered[className] === undefined) {
    cache.registered[className] = serialized.styles;
  }
};
var insertStyles = function insertStyles(cache, serialized, isStringTag) {
  registerStyles(cache, serialized, isStringTag);
  var className = cache.key + "-" + serialized.name;

  if (cache.inserted[serialized.name] === undefined) {
    var current = serialized;

    do {
      cache.insert(serialized === current ? "." + className : '', current, cache.sheet, true);

      current = current.next;
    } while (current !== undefined);
  }
};




/***/ }),

/***/ 46:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Attribute = void 0;
/** @internal */
class Attribute {
    constructor(name, modelName, defaultValue, alwaysWriteJson) {
        this.name = name;
        this.modelName = modelName;
        this.defaultValue = defaultValue;
        this.alwaysWriteJson = alwaysWriteJson;
        this.required = false;
        this.fixed = false;
        this.type = "any";
    }
    setType(value) {
        this.type = value;
        return this;
    }
    setRequired() {
        this.required = true;
        return this;
    }
    setFixed() {
        this.fixed = true;
        return this;
    }
}
exports.Attribute = Attribute;
Attribute.NUMBER = "number";
Attribute.STRING = "string";
Attribute.BOOLEAN = "boolean";
//# sourceMappingURL=Attribute.js.map

/***/ }),

/***/ 94:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FloatingWindow = void 0;
const React = __webpack_require__(6540);
const react_dom_1 = __webpack_require__(961);
const Rect_1 = __webpack_require__(2530);
const Types_1 = __webpack_require__(6643);
/** @internal */
const FloatingWindow = (props) => {
    const { title, id, url, rect, onCloseWindow, onSetWindow, children } = props;
    const popoutWindow = React.useRef(null);
    const timerId = React.useRef(null);
    const [content, setContent] = React.useState(undefined);
    React.useLayoutEffect(() => {
        if (timerId.current) {
            clearTimeout(timerId.current);
        }
        let isMounted = true;
        const r = rect || new Rect_1.Rect(0, 0, 100, 100);
        // Make a local copy of the styles from the current window which will be passed into
        // the floating window. window.document.styleSheets is mutable and we can't guarantee
        // the styles will exist when 'popoutWindow.load' is called below.
        const styles = Array.from(window.document.styleSheets).reduce((result, styleSheet) => {
            let rules = undefined;
            try {
                rules = styleSheet.cssRules;
            }
            catch (e) {
                // styleSheet.cssRules can throw security exception
            }
            try {
                return [
                    ...result,
                    {
                        href: styleSheet.href,
                        type: styleSheet.type,
                        rules: rules ? Array.from(rules).map(rule => rule.cssText) : null,
                    }
                ];
            }
            catch (e) {
                return result;
            }
        }, []);
        popoutWindow.current = window.open(url, id, `left=${r.x},top=${r.y},width=${r.width},height=${r.height}`);
        if (popoutWindow.current !== null) {
            onSetWindow(id, popoutWindow.current);
            // listen for parent unloading to remove all popouts
            window.addEventListener("beforeunload", () => {
                if (popoutWindow.current) {
                    popoutWindow.current.close();
                    popoutWindow.current = null;
                }
            });
            popoutWindow.current.addEventListener("load", () => {
                if (isMounted) {
                    const popoutDocument = popoutWindow.current.document;
                    popoutDocument.title = title;
                    const popoutContent = popoutDocument.createElement("div");
                    popoutContent.className = Types_1.CLASSES.FLEXLAYOUT__FLOATING_WINDOW_CONTENT;
                    popoutDocument.body.appendChild(popoutContent);
                    copyStyles(popoutDocument, styles).then(() => {
                        setContent(popoutContent);
                    });
                    // listen for popout unloading (needs to be after load for safari)
                    popoutWindow.current.addEventListener("beforeunload", () => {
                        onCloseWindow(id);
                    });
                }
            });
        }
        else {
            console.warn(`Unable to open window ${url}`);
            onCloseWindow(id);
        }
        return () => {
            isMounted = false;
            // delay so refresh will close window
            timerId.current = setTimeout(() => {
                if (popoutWindow.current) {
                    popoutWindow.current.close();
                    popoutWindow.current = null;
                }
            }, 0);
        };
    }, []);
    if (content !== undefined) {
        return (0, react_dom_1.createPortal)(children, content);
    }
    else {
        return null;
    }
};
exports.FloatingWindow = FloatingWindow;
/** @internal */
function copyStyles(doc, styleSheets) {
    const head = doc.head;
    const promises = [];
    for (const styleSheet of styleSheets) {
        if (styleSheet.href) {
            // prefer links since they will keep paths to images etc
            const styleElement = doc.createElement("link");
            styleElement.type = styleSheet.type;
            styleElement.rel = "stylesheet";
            styleElement.href = styleSheet.href;
            head.appendChild(styleElement);
            promises.push(new Promise((resolve) => {
                styleElement.onload = () => resolve(true);
            }));
        }
        else {
            if (styleSheet.rules) {
                const style = doc.createElement("style");
                for (const rule of styleSheet.rules) {
                    style.appendChild(doc.createTextNode(rule));
                }
                head.appendChild(style);
            }
        }
    }
    return Promise.all(promises);
}
//# sourceMappingURL=FloatingWindow.js.map

/***/ }),

/***/ 165:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: function() { return /* binding */ cytoscape; }
/* harmony export */ });
/**
 * Copyright (c) 2016-2025, The Cytoscape Consortium.
 *
 * 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.
 */

function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _arrayWithHoles(r) {
  if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
  if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _classCallCheck(a, n) {
  if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(e, r) {
  for (var t = 0; t < r.length; t++) {
    var o = r[t];
    o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  }
}
function _createClass(e, r, t) {
  return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
    writable: false
  }), e;
}
function _createForOfIteratorHelper(r, e) {
  var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (!t) {
    if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
      t && (r = t);
      var n = 0,
        F = function () {};
      return {
        s: F,
        n: function () {
          return n >= r.length ? {
            done: true
          } : {
            done: false,
            value: r[n++]
          };
        },
        e: function (r) {
          throw r;
        },
        f: F
      };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var o,
    a = true,
    u = false;
  return {
    s: function () {
      t = t.call(r);
    },
    n: function () {
      var r = t.next();
      return a = r.done, r;
    },
    e: function (r) {
      u = true, o = r;
    },
    f: function () {
      try {
        a || null == t.return || t.return();
      } finally {
        if (u) throw o;
      }
    }
  };
}
function _defineProperty$1(e, r, t) {
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
    value: t,
    enumerable: true,
    configurable: true,
    writable: true
  }) : e[r] = t, e;
}
function _iterableToArray(r) {
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e,
      n,
      i,
      u,
      a = [],
      f = true,
      o = false;
    try {
      if (i = (t = t.call(r)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = !1;
      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
    } catch (r) {
      o = true, n = r;
    } finally {
      try {
        if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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.");
}
function _slicedToArray(r, e) {
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toConsumableArray(r) {
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _toPrimitive(t, r) {
  if ("object" != typeof t || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (undefined !== e) {
    var i = e.call(t, r);
    if ("object" != typeof i) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (String )(t);
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == typeof i ? i : i + "";
}
function _typeof(o) {
  "@babel/helpers - typeof";

  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, _typeof(o);
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : undefined;
  }
}

var _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef

var navigator = _window ? _window.navigator : null;
_window ? _window.document : null;
var typeofstr = _typeof('');
var typeofobj = _typeof({});
var typeoffn = _typeof(function () {});
var typeofhtmlele = typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement);
var instanceStr = function instanceStr(obj) {
  return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;
};

var string = function string(obj) {
  return obj != null && _typeof(obj) == typeofstr;
};
var fn$6 = function fn(obj) {
  return obj != null && _typeof(obj) === typeoffn;
};
var array = function array(obj) {
  return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);
};
var plainObject = function plainObject(obj) {
  return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;
};
var object = function object(obj) {
  return obj != null && _typeof(obj) === typeofobj;
};
var number$1 = function number(obj) {
  return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);
};
var integer = function integer(obj) {
  return number$1(obj) && Math.floor(obj) === obj;
};
var htmlElement = function htmlElement(obj) {
  if ('undefined' === typeofhtmlele) {
    return undefined;
  } else {
    return null != obj && obj instanceof HTMLElement;
  }
};
var elementOrCollection = function elementOrCollection(obj) {
  return element(obj) || collection(obj);
};
var element = function element(obj) {
  return instanceStr(obj) === 'collection' && obj._private.single;
};
var collection = function collection(obj) {
  return instanceStr(obj) === 'collection' && !obj._private.single;
};
var core = function core(obj) {
  return instanceStr(obj) === 'core';
};
var stylesheet = function stylesheet(obj) {
  return instanceStr(obj) === 'stylesheet';
};
var event = function event(obj) {
  return instanceStr(obj) === 'event';
};
var emptyString = function emptyString(obj) {
  if (obj === undefined || obj === null) {
    // null is empty
    return true;
  } else if (obj === '' || obj.match(/^\s+$/)) {
    return true; // empty string is empty
  }
  return false; // otherwise, we don't know what we've got
};
var domElement = function domElement(obj) {
  if (typeof HTMLElement === 'undefined') {
    return false; // we're not in a browser so it doesn't matter
  } else {
    return obj instanceof HTMLElement;
  }
};
var boundingBox = function boundingBox(obj) {
  return plainObject(obj) && number$1(obj.x1) && number$1(obj.x2) && number$1(obj.y1) && number$1(obj.y2);
};
var promise = function promise(obj) {
  return object(obj) && fn$6(obj.then);
};
var ms = function ms() {
  return navigator && navigator.userAgent.match(/msie|trident|edge/i);
}; // probably a better way to detect this...

var memoize = function memoize(fn, keyFn) {
  if (!keyFn) {
    keyFn = function keyFn() {
      if (arguments.length === 1) {
        return arguments[0];
      } else if (arguments.length === 0) {
        return 'undefined';
      }
      var args = [];
      for (var i = 0; i < arguments.length; i++) {
        args.push(arguments[i]);
      }
      return args.join('$');
    };
  }
  var _memoizedFn = function memoizedFn() {
    var self = this;
    var args = arguments;
    var ret;
    var k = keyFn.apply(self, args);
    var cache = _memoizedFn.cache;
    if (!(ret = cache[k])) {
      ret = cache[k] = fn.apply(self, args);
    }
    return ret;
  };
  _memoizedFn.cache = {};
  return _memoizedFn;
};

var camel2dash = memoize(function (str) {
  return str.replace(/([A-Z])/g, function (v) {
    return '-' + v.toLowerCase();
  });
});
var dash2camel = memoize(function (str) {
  return str.replace(/(-\w)/g, function (v) {
    return v[1].toUpperCase();
  });
});
var prependCamel = memoize(function (prefix, str) {
  return prefix + str[0].toUpperCase() + str.substring(1);
}, function (prefix, str) {
  return prefix + '$' + str;
});
var capitalize = function capitalize(str) {
  if (emptyString(str)) {
    return str;
  }
  return str.charAt(0).toUpperCase() + str.substring(1);
};
var endsWith = function endsWith(string, suffix) {
  return string.slice(-1 * suffix.length) === suffix;
};

var number = '(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))';
var rgba = 'rgb[a]?\\((' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)(?:\\s*,\\s*(' + number + '))?\\)';
var rgbaNoBackRefs = 'rgb[a]?\\((?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)(?:\\s*,\\s*(?:' + number + '))?\\)';
var hsla = 'hsl[a]?\\((' + number + ')\\s*,\\s*(' + number + '[%])\\s*,\\s*(' + number + '[%])(?:\\s*,\\s*(' + number + '))?\\)';
var hslaNoBackRefs = 'hsl[a]?\\((?:' + number + ')\\s*,\\s*(?:' + number + '[%])\\s*,\\s*(?:' + number + '[%])(?:\\s*,\\s*(?:' + number + '))?\\)';
var hex3 = '\\#[0-9a-fA-F]{3}';
var hex6 = '\\#[0-9a-fA-F]{6}';

var ascending = function ascending(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
};
var descending = function descending(a, b) {
  return -1 * ascending(a, b);
};

var extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
  var args = arguments;
  for (var i = 1; i < args.length; i++) {
    var obj = args[i];
    if (obj == null) {
      continue;
    }
    var keys = Object.keys(obj);
    for (var j = 0; j < keys.length; j++) {
      var k = keys[j];
      tgt[k] = obj[k];
    }
  }
  return tgt;
};

// get [r, g, b] from #abc or #aabbcc
var hex2tuple = function hex2tuple(hex) {
  if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {
    return;
  }
  var shortHex = hex.length === 4;
  var r, g, b;
  var base = 16;
  if (shortHex) {
    r = parseInt(hex[1] + hex[1], base);
    g = parseInt(hex[2] + hex[2], base);
    b = parseInt(hex[3] + hex[3], base);
  } else {
    r = parseInt(hex[1] + hex[2], base);
    g = parseInt(hex[3] + hex[4], base);
    b = parseInt(hex[5] + hex[6], base);
  }
  return [r, g, b];
};

// get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)
var hsl2tuple = function hsl2tuple(hsl) {
  var ret;
  var h, s, l, a, r, g, b;
  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;
  }
  var m = new RegExp('^' + hsla + '$').exec(hsl);
  if (m) {
    // get hue
    h = parseInt(m[1]);
    if (h < 0) {
      h = (360 - -1 * h % 360) % 360;
    } else if (h > 360) {
      h = h % 360;
    }
    h /= 360; // normalise on [0, 1]

    s = parseFloat(m[2]);
    if (s < 0 || s > 100) {
      return;
    } // saturation is [0, 100]
    s = s / 100; // normalise on [0, 1]

    l = parseFloat(m[3]);
    if (l < 0 || l > 100) {
      return;
    } // lightness is [0, 100]
    l = l / 100; // normalise on [0, 1]

    a = m[4];
    if (a !== undefined) {
      a = parseFloat(a);
      if (a < 0 || a > 1) {
        return;
      } // alpha is [0, 1]
    }

    // now, convert to rgb
    // code from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
    if (s === 0) {
      r = g = b = Math.round(l * 255); // achromatic
    } else {
      var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      var p = 2 * l - q;
      r = Math.round(255 * hue2rgb(p, q, h + 1 / 3));
      g = Math.round(255 * hue2rgb(p, q, h));
      b = Math.round(255 * hue2rgb(p, q, h - 1 / 3));
    }
    ret = [r, g, b, a];
  }
  return ret;
};

// get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)
var rgb2tuple = function rgb2tuple(rgb) {
  var ret;
  var m = new RegExp('^' + rgba + '$').exec(rgb);
  if (m) {
    ret = [];
    var isPct = [];
    for (var i = 1; i <= 3; i++) {
      var channel = m[i];
      if (channel[channel.length - 1] === '%') {
        isPct[i] = true;
      }
      channel = parseFloat(channel);
      if (isPct[i]) {
        channel = channel / 100 * 255; // normalise to [0, 255]
      }
      if (channel < 0 || channel > 255) {
        return;
      } // invalid channel value

      ret.push(Math.floor(channel));
    }
    var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];
    var allArePct = isPct[1] && isPct[2] && isPct[3];
    if (atLeastOneIsPct && !allArePct) {
      return;
    } // must all be percent values if one is

    var alpha = m[4];
    if (alpha !== undefined) {
      alpha = parseFloat(alpha);
      if (alpha < 0 || alpha > 1) {
        return;
      } // invalid alpha value

      ret.push(alpha);
    }
  }
  return ret;
};
var colorname2tuple = function colorname2tuple(color) {
  return colors[color.toLowerCase()];
};
var color2tuple = function color2tuple(color) {
  return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);
};
var colors = {
  // special colour names
  transparent: [0, 0, 0, 0],
  // NB alpha === 0

  // regular colours
  aliceblue: [240, 248, 255],
  antiquewhite: [250, 235, 215],
  aqua: [0, 255, 255],
  aquamarine: [127, 255, 212],
  azure: [240, 255, 255],
  beige: [245, 245, 220],
  bisque: [255, 228, 196],
  black: [0, 0, 0],
  blanchedalmond: [255, 235, 205],
  blue: [0, 0, 255],
  blueviolet: [138, 43, 226],
  brown: [165, 42, 42],
  burlywood: [222, 184, 135],
  cadetblue: [95, 158, 160],
  chartreuse: [127, 255, 0],
  chocolate: [210, 105, 30],
  coral: [255, 127, 80],
  cornflowerblue: [100, 149, 237],
  cornsilk: [255, 248, 220],
  crimson: [220, 20, 60],
  cyan: [0, 255, 255],
  darkblue: [0, 0, 139],
  darkcyan: [0, 139, 139],
  darkgoldenrod: [184, 134, 11],
  darkgray: [169, 169, 169],
  darkgreen: [0, 100, 0],
  darkgrey: [169, 169, 169],
  darkkhaki: [189, 183, 107],
  darkmagenta: [139, 0, 139],
  darkolivegreen: [85, 107, 47],
  darkorange: [255, 140, 0],
  darkorchid: [153, 50, 204],
  darkred: [139, 0, 0],
  darksalmon: [233, 150, 122],
  darkseagreen: [143, 188, 143],
  darkslateblue: [72, 61, 139],
  darkslategray: [47, 79, 79],
  darkslategrey: [47, 79, 79],
  darkturquoise: [0, 206, 209],
  darkviolet: [148, 0, 211],
  deeppink: [255, 20, 147],
  deepskyblue: [0, 191, 255],
  dimgray: [105, 105, 105],
  dimgrey: [105, 105, 105],
  dodgerblue: [30, 144, 255],
  firebrick: [178, 34, 34],
  floralwhite: [255, 250, 240],
  forestgreen: [34, 139, 34],
  fuchsia: [255, 0, 255],
  gainsboro: [220, 220, 220],
  ghostwhite: [248, 248, 255],
  gold: [255, 215, 0],
  goldenrod: [218, 165, 32],
  gray: [128, 128, 128],
  grey: [128, 128, 128],
  green: [0, 128, 0],
  greenyellow: [173, 255, 47],
  honeydew: [240, 255, 240],
  hotpink: [255, 105, 180],
  indianred: [205, 92, 92],
  indigo: [75, 0, 130],
  ivory: [255, 255, 240],
  khaki: [240, 230, 140],
  lavender: [230, 230, 250],
  lavenderblush: [255, 240, 245],
  lawngreen: [124, 252, 0],
  lemonchiffon: [255, 250, 205],
  lightblue: [173, 216, 230],
  lightcoral: [240, 128, 128],
  lightcyan: [224, 255, 255],
  lightgoldenrodyellow: [250, 250, 210],
  lightgray: [211, 211, 211],
  lightgreen: [144, 238, 144],
  lightgrey: [211, 211, 211],
  lightpink: [255, 182, 193],
  lightsalmon: [255, 160, 122],
  lightseagreen: [32, 178, 170],
  lightskyblue: [135, 206, 250],
  lightslategray: [119, 136, 153],
  lightslategrey: [119, 136, 153],
  lightsteelblue: [176, 196, 222],
  lightyellow: [255, 255, 224],
  lime: [0, 255, 0],
  limegreen: [50, 205, 50],
  linen: [250, 240, 230],
  magenta: [255, 0, 255],
  maroon: [128, 0, 0],
  mediumaquamarine: [102, 205, 170],
  mediumblue: [0, 0, 205],
  mediumorchid: [186, 85, 211],
  mediumpurple: [147, 112, 219],
  mediumseagreen: [60, 179, 113],
  mediumslateblue: [123, 104, 238],
  mediumspringgreen: [0, 250, 154],
  mediumturquoise: [72, 209, 204],
  mediumvioletred: [199, 21, 133],
  midnightblue: [25, 25, 112],
  mintcream: [245, 255, 250],
  mistyrose: [255, 228, 225],
  moccasin: [255, 228, 181],
  navajowhite: [255, 222, 173],
  navy: [0, 0, 128],
  oldlace: [253, 245, 230],
  olive: [128, 128, 0],
  olivedrab: [107, 142, 35],
  orange: [255, 165, 0],
  orangered: [255, 69, 0],
  orchid: [218, 112, 214],
  palegoldenrod: [238, 232, 170],
  palegreen: [152, 251, 152],
  paleturquoise: [175, 238, 238],
  palevioletred: [219, 112, 147],
  papayawhip: [255, 239, 213],
  peachpuff: [255, 218, 185],
  peru: [205, 133, 63],
  pink: [255, 192, 203],
  plum: [221, 160, 221],
  powderblue: [176, 224, 230],
  purple: [128, 0, 128],
  red: [255, 0, 0],
  rosybrown: [188, 143, 143],
  royalblue: [65, 105, 225],
  saddlebrown: [139, 69, 19],
  salmon: [250, 128, 114],
  sandybrown: [244, 164, 96],
  seagreen: [46, 139, 87],
  seashell: [255, 245, 238],
  sienna: [160, 82, 45],
  silver: [192, 192, 192],
  skyblue: [135, 206, 235],
  slateblue: [106, 90, 205],
  slategray: [112, 128, 144],
  slategrey: [112, 128, 144],
  snow: [255, 250, 250],
  springgreen: [0, 255, 127],
  steelblue: [70, 130, 180],
  tan: [210, 180, 140],
  teal: [0, 128, 128],
  thistle: [216, 191, 216],
  tomato: [255, 99, 71],
  turquoise: [64, 224, 208],
  violet: [238, 130, 238],
  wheat: [245, 222, 179],
  white: [255, 255, 255],
  whitesmoke: [245, 245, 245],
  yellow: [255, 255, 0],
  yellowgreen: [154, 205, 50]
};

// sets the value in a map (map may not be built)
var setMap = function setMap(options) {
  var obj = options.map;
  var keys = options.keys;
  var l = keys.length;
  for (var i = 0; i < l; i++) {
    var key = keys[i];
    if (plainObject(key)) {
      throw Error('Tried to set map with object key');
    }
    if (i < keys.length - 1) {
      // extend the map if necessary
      if (obj[key] == null) {
        obj[key] = {};
      }
      obj = obj[key];
    } else {
      // set the value
      obj[key] = options.value;
    }
  }
};

// gets the value in a map even if it's not built in places
var getMap = function getMap(options) {
  var obj = options.map;
  var keys = options.keys;
  var l = keys.length;
  for (var i = 0; i < l; i++) {
    var key = keys[i];
    if (plainObject(key)) {
      throw Error('Tried to get map with object key');
    }
    obj = obj[key];
    if (obj == null) {
      return obj;
    }
  }
  return obj;
};

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

/**
 * 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
 */

var isObject_1;
var hasRequiredIsObject;

function requireIsObject () {
	if (hasRequiredIsObject) return isObject_1;
	hasRequiredIsObject = 1;
	function isObject(value) {
	  var type = typeof value;
	  return value != null && (type == 'object' || type == 'function');
	}

	isObject_1 = isObject;
	return isObject_1;
}

/** Detect free variable `global` from Node.js. */

var _freeGlobal;
var hasRequired_freeGlobal;

function require_freeGlobal () {
	if (hasRequired_freeGlobal) return _freeGlobal;
	hasRequired_freeGlobal = 1;
	var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;

	_freeGlobal = freeGlobal;
	return _freeGlobal;
}

var _root;
var hasRequired_root;

function require_root () {
	if (hasRequired_root) return _root;
	hasRequired_root = 1;
	var freeGlobal = require_freeGlobal();

	/** 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')();

	_root = root;
	return _root;
}

var now_1;
var hasRequiredNow;

function requireNow () {
	if (hasRequiredNow) return now_1;
	hasRequiredNow = 1;
	var root = require_root();

	/**
	 * 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();
	};

	now_1 = now;
	return now_1;
}

/** Used to match a single whitespace character. */

var _trimmedEndIndex;
var hasRequired_trimmedEndIndex;

function require_trimmedEndIndex () {
	if (hasRequired_trimmedEndIndex) return _trimmedEndIndex;
	hasRequired_trimmedEndIndex = 1;
	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;
	}

	_trimmedEndIndex = trimmedEndIndex;
	return _trimmedEndIndex;
}

var _baseTrim;
var hasRequired_baseTrim;

function require_baseTrim () {
	if (hasRequired_baseTrim) return _baseTrim;
	hasRequired_baseTrim = 1;
	var trimmedEndIndex = require_trimmedEndIndex();

	/** 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;
	}

	_baseTrim = baseTrim;
	return _baseTrim;
}

var _Symbol;
var hasRequired_Symbol;

function require_Symbol () {
	if (hasRequired_Symbol) return _Symbol;
	hasRequired_Symbol = 1;
	var root = require_root();

	/** Built-in value references. */
	var Symbol = root.Symbol;

	_Symbol = Symbol;
	return _Symbol;
}

var _getRawTag;
var hasRequired_getRawTag;

function require_getRawTag () {
	if (hasRequired_getRawTag) return _getRawTag;
	hasRequired_getRawTag = 1;
	var Symbol = require_Symbol();

	/** 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;
	}

	_getRawTag = getRawTag;
	return _getRawTag;
}

/** Used for built-in method references. */

var _objectToString;
var hasRequired_objectToString;

function require_objectToString () {
	if (hasRequired_objectToString) return _objectToString;
	hasRequired_objectToString = 1;
	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);
	}

	_objectToString = objectToString;
	return _objectToString;
}

var _baseGetTag;
var hasRequired_baseGetTag;

function require_baseGetTag () {
	if (hasRequired_baseGetTag) return _baseGetTag;
	hasRequired_baseGetTag = 1;
	var Symbol = require_Symbol(),
	    getRawTag = require_getRawTag(),
	    objectToString = require_objectToString();

	/** `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);
	}

	_baseGetTag = baseGetTag;
	return _baseGetTag;
}

/**
 * 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
 */

var isObjectLike_1;
var hasRequiredIsObjectLike;

function requireIsObjectLike () {
	if (hasRequiredIsObjectLike) return isObjectLike_1;
	hasRequiredIsObjectLike = 1;
	function isObjectLike(value) {
	  return value != null && typeof value == 'object';
	}

	isObjectLike_1 = isObjectLike;
	return isObjectLike_1;
}

var isSymbol_1;
var hasRequiredIsSymbol;

function requireIsSymbol () {
	if (hasRequiredIsSymbol) return isSymbol_1;
	hasRequiredIsSymbol = 1;
	var baseGetTag = require_baseGetTag(),
	    isObjectLike = requireIsObjectLike();

	/** `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);
	}

	isSymbol_1 = isSymbol;
	return isSymbol_1;
}

var toNumber_1;
var hasRequiredToNumber;

function requireToNumber () {
	if (hasRequiredToNumber) return toNumber_1;
	hasRequiredToNumber = 1;
	var baseTrim = require_baseTrim(),
	    isObject = requireIsObject(),
	    isSymbol = requireIsSymbol();

	/** 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 (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 = baseTrim(value);
	  var isBinary = reIsBinary.test(value);
	  return (isBinary || reIsOctal.test(value))
	    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
	    : (reIsBadHex.test(value) ? NAN : +value);
	}

	toNumber_1 = toNumber;
	return toNumber_1;
}

var debounce_1;
var hasRequiredDebounce;

function requireDebounce () {
	if (hasRequiredDebounce) return debounce_1;
	hasRequiredDebounce = 1;
	var isObject = requireIsObject(),
	    now = requireNow(),
	    toNumber = requireToNumber();

	/** 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;
	}

	debounce_1 = debounce;
	return debounce_1;
}

var debounceExports = requireDebounce();
var debounce = /*@__PURE__*/getDefaultExportFromCjs(debounceExports);

var performance$1 = _window ? _window.performance : null;
var pnow = performance$1 && performance$1.now ? function () {
  return performance$1.now();
} : function () {
  return Date.now();
};
var raf = function () {
  if (_window) {
    if (_window.requestAnimationFrame) {
      return function (fn) {
        _window.requestAnimationFrame(fn);
      };
    } else if (_window.mozRequestAnimationFrame) {
      return function (fn) {
        _window.mozRequestAnimationFrame(fn);
      };
    } else if (_window.webkitRequestAnimationFrame) {
      return function (fn) {
        _window.webkitRequestAnimationFrame(fn);
      };
    } else if (_window.msRequestAnimationFrame) {
      return function (fn) {
        _window.msRequestAnimationFrame(fn);
      };
    }
  }
  return function (fn) {
    if (fn) {
      setTimeout(function () {
        fn(pnow());
      }, 1000 / 60);
    }
  };
}();
var requestAnimationFrame = function requestAnimationFrame(fn) {
  return raf(fn);
};
var performanceNow = pnow;

var DEFAULT_HASH_SEED = 9261;
var K = 65599; // 37 also works pretty well
var DEFAULT_HASH_SEED_ALT = 5381;
var hashIterableInts = function hashIterableInts(iterator) {
  var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  // sdbm/string-hash
  var hash = seed;
  var entry;
  for (;;) {
    entry = iterator.next();
    if (entry.done) {
      break;
    }
    hash = hash * K + entry.value | 0;
  }
  return hash;
};
var hashInt = function hashInt(num) {
  var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  // sdbm/string-hash
  return seed * K + num | 0;
};
var hashIntAlt = function hashIntAlt(num) {
  var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED_ALT;
  // djb2/string-hash
  return (seed << 5) + seed + num | 0;
};
var combineHashes = function combineHashes(hash1, hash2) {
  return hash1 * 0x200000 + hash2;
};
var combineHashesArray = function combineHashesArray(hashes) {
  return hashes[0] * 0x200000 + hashes[1];
};
var hashArrays = function hashArrays(hashes1, hashes2) {
  return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];
};
var hashIntsArray = function hashIntsArray(ints, seed) {
  var entry = {
    value: 0,
    done: false
  };
  var i = 0;
  var length = ints.length;
  var iterator = {
    next: function next() {
      if (i < length) {
        entry.value = ints[i++];
      } else {
        entry.done = true;
      }
      return entry;
    }
  };
  return hashIterableInts(iterator, seed);
};
var hashString = function hashString(str, seed) {
  var entry = {
    value: 0,
    done: false
  };
  var i = 0;
  var length = str.length;
  var iterator = {
    next: function next() {
      if (i < length) {
        entry.value = str.charCodeAt(i++);
      } else {
        entry.done = true;
      }
      return entry;
    }
  };
  return hashIterableInts(iterator, seed);
};
var hashStrings = function hashStrings() {
  return hashStringsArray(arguments);
};
var hashStringsArray = function hashStringsArray(strs) {
  var hash;
  for (var i = 0; i < strs.length; i++) {
    var str = strs[i];
    if (i === 0) {
      hash = hashString(str);
    } else {
      hash = hashString(str, hash);
    }
  }
  return hash;
};

function rotatePoint(x, y, centerX, centerY, angleDegrees) {
  var angleRadians = angleDegrees * Math.PI / 180;
  var rotatedX = Math.cos(angleRadians) * (x - centerX) - Math.sin(angleRadians) * (y - centerY) + centerX;
  var rotatedY = Math.sin(angleRadians) * (x - centerX) + Math.cos(angleRadians) * (y - centerY) + centerY;
  return {
    x: rotatedX,
    y: rotatedY
  };
}
var movePointByBoxAspect = function movePointByBoxAspect(x, y, boxX, boxY, skewX, skewY) {
  return {
    x: (x - boxX) * skewX + boxX,
    y: (y - boxY) * skewY + boxY
  };
};
function rotatePosAndSkewByBox(pos, box, angleDegrees) {
  if (angleDegrees === 0) return pos;
  var centerX = (box.x1 + box.x2) / 2;
  var centerY = (box.y1 + box.y2) / 2;
  var skewX = box.w / box.h;
  var skewY = 1 / skewX;
  var rotated = rotatePoint(pos.x, pos.y, centerX, centerY, angleDegrees);
  var skewed = movePointByBoxAspect(rotated.x, rotated.y, centerX, centerY, skewX, skewY);
  return {
    x: skewed.x,
    y: skewed.y
  };
}

var warningsEnabled = true;
var warnSupported = console.warn != null;
var traceSupported = console.trace != null;
var MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;
var trueify = function trueify() {
  return true;
};
var falsify = function falsify() {
  return false;
};
var zeroify = function zeroify() {
  return 0;
};
var noop$1 = function noop() {};
var error = function error(msg) {
  throw new Error(msg);
};
var warnings = function warnings(enabled) {
  if (enabled !== undefined) {
    warningsEnabled = !!enabled;
  } else {
    return warningsEnabled;
  }
};
var warn = function warn(msg) {
  if (!warnings()) {
    return;
  }
  if (warnSupported) {
    console.warn(msg);
  } else {
    console.log(msg);
    if (traceSupported) {
      console.trace();
    }
  }
};
var clone = function clone(obj) {
  return extend({}, obj);
};

// gets a shallow copy of the argument
var copy = function copy(obj) {
  if (obj == null) {
    return obj;
  }
  if (array(obj)) {
    return obj.slice();
  } else if (plainObject(obj)) {
    return clone(obj);
  } else {
    return obj;
  }
};
var copyArray = function copyArray(arr) {
  return arr.slice();
};
var uuid = function uuid(a, b /* placeholders */) {
  for (
  // loop :)
  b = a = '';
  // b - result , a - numeric letiable
  a++ < 36;
  //
  b += a * 51 & 52 // if "a" is not 9 or 14 or 19 or 24
  ?
  //  return a random number or 4
  (a ^ 15 // if "a" is not 15
  ?
  // generate a random number from 0 to 15
  8 ^ Math.random() * (a ^ 20 ? 16 : 4) // unless "a" is 20, in which case a random number from 8 to 11
  : 4 //  otherwise 4
  ).toString(16) : '-' //  in other cases (if "a" is 9,14,19,24) insert "-"
  );
  return b;
};
var _staticEmptyObject = {};
var staticEmptyObject = function staticEmptyObject() {
  return _staticEmptyObject;
};
var defaults$g = function defaults(_defaults) {
  var keys = Object.keys(_defaults);
  return function (opts) {
    var filledOpts = {};
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var optVal = opts == null ? undefined : opts[key];
      filledOpts[key] = optVal === undefined ? _defaults[key] : optVal;
    }
    return filledOpts;
  };
};
var removeFromArray = function removeFromArray(arr, ele, oneCopy) {
  for (var i = arr.length - 1; i >= 0; i--) {
    if (arr[i] === ele) {
      arr.splice(i, 1);
    }
  }
};
var clearArray = function clearArray(arr) {
  arr.splice(0, arr.length);
};
var push = function push(arr, otherArr) {
  for (var i = 0; i < otherArr.length; i++) {
    var el = otherArr[i];
    arr.push(el);
  }
};
var getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {
  if (prefix) {
    propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  }
  return obj[propName];
};
var setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {
  if (prefix) {
    propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  }
  obj[propName] = value;
};

/* global Map */
var ObjectMap = /*#__PURE__*/function () {
  function ObjectMap() {
    _classCallCheck(this, ObjectMap);
    this._obj = {};
  }
  return _createClass(ObjectMap, [{
    key: "set",
    value: function set(key, val) {
      this._obj[key] = val;
      return this;
    }
  }, {
    key: "delete",
    value: function _delete(key) {
      this._obj[key] = undefined;
      return this;
    }
  }, {
    key: "clear",
    value: function clear() {
      this._obj = {};
    }
  }, {
    key: "has",
    value: function has(key) {
      return this._obj[key] !== undefined;
    }
  }, {
    key: "get",
    value: function get(key) {
      return this._obj[key];
    }
  }]);
}();
var Map$1 = typeof Map !== 'undefined' ? Map : ObjectMap;

/* global Set */

var undef = "undefined" ;
var ObjectSet = /*#__PURE__*/function () {
  function ObjectSet(arrayOrObjectSet) {
    _classCallCheck(this, ObjectSet);
    this._obj = Object.create(null);
    this.size = 0;
    if (arrayOrObjectSet != null) {
      var arr;
      if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {
        arr = arrayOrObjectSet.toArray();
      } else {
        arr = arrayOrObjectSet;
      }
      for (var i = 0; i < arr.length; i++) {
        this.add(arr[i]);
      }
    }
  }
  return _createClass(ObjectSet, [{
    key: "instanceString",
    value: function instanceString() {
      return 'set';
    }
  }, {
    key: "add",
    value: function add(val) {
      var o = this._obj;
      if (o[val] !== 1) {
        o[val] = 1;
        this.size++;
      }
    }
  }, {
    key: "delete",
    value: function _delete(val) {
      var o = this._obj;
      if (o[val] === 1) {
        o[val] = 0;
        this.size--;
      }
    }
  }, {
    key: "clear",
    value: function clear() {
      this._obj = Object.create(null);
    }
  }, {
    key: "has",
    value: function has(val) {
      return this._obj[val] === 1;
    }
  }, {
    key: "toArray",
    value: function toArray() {
      var _this = this;
      return Object.keys(this._obj).filter(function (key) {
        return _this.has(key);
      });
    }
  }, {
    key: "forEach",
    value: function forEach(callback, thisArg) {
      return this.toArray().forEach(callback, thisArg);
    }
  }]);
}();
var Set$1 = (typeof Set === "undefined" ? "undefined" : _typeof(Set)) !== undef ? Set : ObjectSet;

// represents a node or an edge
var Element = function Element(cy, params) {
  var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  if (cy === undefined || params === undefined || !core(cy)) {
    error('An element must have a core reference and parameters set');
    return;
  }
  var group = params.group;

  // try to automatically infer the group if unspecified
  if (group == null) {
    if (params.data && params.data.source != null && params.data.target != null) {
      group = 'edges';
    } else {
      group = 'nodes';
    }
  }

  // validate group
  if (group !== 'nodes' && group !== 'edges') {
    error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');
    return;
  }

  // make the element array-like, just like a collection
  this.length = 1;
  this[0] = this;

  // NOTE: when something is added here, add also to ele.json()
  var _p = this._private = {
    cy: cy,
    single: true,
    // indicates this is an element
    data: params.data || {},
    // data object
    position: params.position || {
      x: 0,
      y: 0
    },
    // (x, y) position pair
    autoWidth: undefined,
    // width and height of nodes calculated by the renderer when set to special 'auto' value
    autoHeight: undefined,
    autoPadding: undefined,
    compoundBoundsClean: false,
    // whether the compound dimensions need to be recalculated the next time dimensions are read
    listeners: [],
    // array of bound listeners
    group: group,
    // string; 'nodes' or 'edges'
    style: {},
    // properties as set by the style
    rstyle: {},
    // properties for style sent from the renderer to the core
    styleCxts: [],
    // applied style contexts from the styler
    styleKeys: {},
    // per-group keys of style property values
    removed: true,
    // whether it's inside the vis; true if removed (set true here since we call restore)
    selected: params.selected ? true : false,
    // whether it's selected
    selectable: params.selectable === undefined ? true : params.selectable ? true : false,
    // whether it's selectable
    locked: params.locked ? true : false,
    // whether the element is locked (cannot be moved)
    grabbed: false,
    // whether the element is grabbed by the mouse; renderer sets this privately
    grabbable: params.grabbable === undefined ? true : params.grabbable ? true : false,
    // whether the element can be grabbed
    pannable: params.pannable === undefined ? group === 'edges' ? true : false : params.pannable ? true : false,
    // whether the element has passthrough panning enabled
    active: false,
    // whether the element is active from user interaction
    classes: new Set$1(),
    // map ( className => true )
    animation: {
      // object for currently-running animations
      current: [],
      queue: []
    },
    rscratch: {},
    // object in which the renderer can store information
    scratch: params.scratch || {},
    // scratch objects
    edges: [],
    // array of connected edges
    children: [],
    // array of children
    parent: params.parent && params.parent.isNode() ? params.parent : null,
    // parent ref
    traversalCache: {},
    // cache of output of traversal functions
    backgrounding: false,
    // whether background images are loading
    bbCache: null,
    // cache of the current bounding box
    bbCacheShift: {
      x: 0,
      y: 0
    },
    // shift applied to cached bb to be applied on next get
    bodyBounds: null,
    // bounds cache of element body, w/o overlay
    overlayBounds: null,
    // bounds cache of element body, including overlay
    labelBounds: {
      // bounds cache of labels
      all: null,
      source: null,
      target: null,
      main: null
    },
    arrowBounds: {
      // bounds cache of edge arrows
      source: null,
      target: null,
      'mid-source': null,
      'mid-target': null
    }
  };
  if (_p.position.x == null) {
    _p.position.x = 0;
  }
  if (_p.position.y == null) {
    _p.position.y = 0;
  }

  // renderedPosition overrides if specified
  if (params.renderedPosition) {
    var rpos = params.renderedPosition;
    var pan = cy.pan();
    var zoom = cy.zoom();
    _p.position = {
      x: (rpos.x - pan.x) / zoom,
      y: (rpos.y - pan.y) / zoom
    };
  }
  var classes = [];
  if (array(params.classes)) {
    classes = params.classes;
  } else if (string(params.classes)) {
    classes = params.classes.split(/\s+/);
  }
  for (var i = 0, l = classes.length; i < l; i++) {
    var cls = classes[i];
    if (!cls || cls === '') {
      continue;
    }
    _p.classes.add(cls);
  }
  this.createEmitter();
  if (restore === undefined || restore) {
    this.restore();
  }
  var bypass = params.style || params.css;
  if (bypass) {
    warn('Setting a `style` bypass at element creation should be done only when absolutely necessary.  Try to use the stylesheet instead.');
    this.style(bypass);
  }
};

var defineSearch = function defineSearch(params) {
  params = {
    bfs: params.bfs || !params.dfs,
    dfs: params.dfs || !params.bfs
  };

  // from pseudocode on wikipedia
  return function searchFn(roots, fn, directed) {
    var options;
    if (plainObject(roots) && !elementOrCollection(roots)) {
      options = roots;
      roots = options.roots || options.root;
      fn = options.visit;
      directed = options.directed;
    }
    directed = arguments.length === 2 && !fn$6(fn) ? fn : directed;
    fn = fn$6(fn) ? fn : function () {};
    var cy = this._private.cy;
    var v = roots = string(roots) ? this.filter(roots) : roots;
    var Q = [];
    var connectedNodes = [];
    var connectedBy = {};
    var id2depth = {};
    var V = {};
    var j = 0;
    var found;
    var _this$byGroup = this.byGroup(),
      nodes = _this$byGroup.nodes,
      edges = _this$byGroup.edges;

    // enqueue v
    for (var i = 0; i < v.length; i++) {
      var vi = v[i];
      var viId = vi.id();
      if (vi.isNode()) {
        Q.unshift(vi);
        if (params.bfs) {
          V[viId] = true;
          connectedNodes.push(vi);
        }
        id2depth[viId] = 0;
      }
    }
    var _loop = function _loop() {
        var v = params.bfs ? Q.shift() : Q.pop();
        var vId = v.id();
        if (params.dfs) {
          if (V[vId]) {
            return 0; // continue
          }
          V[vId] = true;
          connectedNodes.push(v);
        }
        var depth = id2depth[vId];
        var prevEdge = connectedBy[vId];
        var src = prevEdge != null ? prevEdge.source() : null;
        var tgt = prevEdge != null ? prevEdge.target() : null;
        var prevNode = prevEdge == null ? undefined : v.same(src) ? tgt[0] : src[0];
        var ret;
        ret = fn(v, prevEdge, prevNode, j++, depth);
        if (ret === true) {
          found = v;
          return 1; // break
        }
        if (ret === false) {
          return 1; // break
        }
        var vwEdges = v.connectedEdges().filter(function (e) {
          return (!directed || e.source().same(v)) && edges.has(e);
        });
        for (var _i2 = 0; _i2 < vwEdges.length; _i2++) {
          var e = vwEdges[_i2];
          var w = e.connectedNodes().filter(function (n) {
            return !n.same(v) && nodes.has(n);
          });
          var wId = w.id();
          if (w.length !== 0 && !V[wId]) {
            w = w[0];
            Q.push(w);
            if (params.bfs) {
              V[wId] = true;
              connectedNodes.push(w);
            }
            connectedBy[wId] = e;
            id2depth[wId] = id2depth[vId] + 1;
          }
        }
      },
      _ret;
    while (Q.length !== 0) {
      _ret = _loop();
      if (_ret === 0) continue;
      if (_ret === 1) break;
    }
    var connectedEles = cy.collection();
    for (var _i = 0; _i < connectedNodes.length; _i++) {
      var node = connectedNodes[_i];
      var edge = connectedBy[node.id()];
      if (edge != null) {
        connectedEles.push(edge);
      }
      connectedEles.push(node);
    }
    return {
      path: cy.collection(connectedEles),
      found: cy.collection(found)
    };
  };
};

// search, spanning trees, etc
var elesfn$v = {
  breadthFirstSearch: defineSearch({
    bfs: true
  }),
  depthFirstSearch: defineSearch({
    dfs: true
  })
};

// nice, short mathematical alias
elesfn$v.bfs = elesfn$v.breadthFirstSearch;
elesfn$v.dfs = elesfn$v.depthFirstSearch;

var heap$2 = {exports: {}};

var heap$1 = heap$2.exports;

var hasRequiredHeap$1;

function requireHeap$1 () {
	if (hasRequiredHeap$1) return heap$2.exports;
	hasRequiredHeap$1 = 1;
	(function (module, exports) {
		// Generated by CoffeeScript 1.8.0
		(function() {
		  var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;

		  floor = Math.floor, min = Math.min;


		  /*
		  Default comparison function to be used
		   */

		  defaultCmp = function(x, y) {
		    if (x < y) {
		      return -1;
		    }
		    if (x > y) {
		      return 1;
		    }
		    return 0;
		  };


		  /*
		  Insert item x in list a, and keep it sorted assuming a is sorted.
		  
		  If x is already in a, insert it to the right of the rightmost x.
		  
		  Optional args lo (default 0) and hi (default a.length) bound the slice
		  of a to be searched.
		   */

		  insort = function(a, x, lo, hi, cmp) {
		    var mid;
		    if (lo == null) {
		      lo = 0;
		    }
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    if (lo < 0) {
		      throw new Error('lo must be non-negative');
		    }
		    if (hi == null) {
		      hi = a.length;
		    }
		    while (lo < hi) {
		      mid = floor((lo + hi) / 2);
		      if (cmp(x, a[mid]) < 0) {
		        hi = mid;
		      } else {
		        lo = mid + 1;
		      }
		    }
		    return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
		  };


		  /*
		  Push item onto heap, maintaining the heap invariant.
		   */

		  heappush = function(array, item, cmp) {
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    array.push(item);
		    return _siftdown(array, 0, array.length - 1, cmp);
		  };


		  /*
		  Pop the smallest item off the heap, maintaining the heap invariant.
		   */

		  heappop = function(array, cmp) {
		    var lastelt, returnitem;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    lastelt = array.pop();
		    if (array.length) {
		      returnitem = array[0];
		      array[0] = lastelt;
		      _siftup(array, 0, cmp);
		    } else {
		      returnitem = lastelt;
		    }
		    return returnitem;
		  };


		  /*
		  Pop and return the current smallest value, and add the new item.
		  
		  This is more efficient than heappop() followed by heappush(), and can be
		  more appropriate when using a fixed size heap. Note that the value
		  returned may be larger than item! That constrains reasonable use of
		  this routine unless written as part of a conditional replacement:
		      if item > array[0]
		        item = heapreplace(array, item)
		   */

		  heapreplace = function(array, item, cmp) {
		    var returnitem;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    returnitem = array[0];
		    array[0] = item;
		    _siftup(array, 0, cmp);
		    return returnitem;
		  };


		  /*
		  Fast version of a heappush followed by a heappop.
		   */

		  heappushpop = function(array, item, cmp) {
		    var _ref;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    if (array.length && cmp(array[0], item) < 0) {
		      _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
		      _siftup(array, 0, cmp);
		    }
		    return item;
		  };


		  /*
		  Transform list into a heap, in-place, in O(array.length) time.
		   */

		  heapify = function(array, cmp) {
		    var i, _i, _len, _ref1, _results, _results1;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    _ref1 = (function() {
		      _results1 = [];
		      for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
		      return _results1;
		    }).apply(this).reverse();
		    _results = [];
		    for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
		      i = _ref1[_i];
		      _results.push(_siftup(array, i, cmp));
		    }
		    return _results;
		  };


		  /*
		  Update the position of the given item in the heap.
		  This function should be called every time the item is being modified.
		   */

		  updateItem = function(array, item, cmp) {
		    var pos;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    pos = array.indexOf(item);
		    if (pos === -1) {
		      return;
		    }
		    _siftdown(array, 0, pos, cmp);
		    return _siftup(array, pos, cmp);
		  };


		  /*
		  Find the n largest elements in a dataset.
		   */

		  nlargest = function(array, n, cmp) {
		    var elem, result, _i, _len, _ref;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    result = array.slice(0, n);
		    if (!result.length) {
		      return result;
		    }
		    heapify(result, cmp);
		    _ref = array.slice(n);
		    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
		      elem = _ref[_i];
		      heappushpop(result, elem, cmp);
		    }
		    return result.sort(cmp).reverse();
		  };


		  /*
		  Find the n smallest elements in a dataset.
		   */

		  nsmallest = function(array, n, cmp) {
		    var elem, los, result, _i, _j, _len, _ref, _ref1, _results;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    if (n * 10 <= array.length) {
		      result = array.slice(0, n).sort(cmp);
		      if (!result.length) {
		        return result;
		      }
		      los = result[result.length - 1];
		      _ref = array.slice(n);
		      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
		        elem = _ref[_i];
		        if (cmp(elem, los) < 0) {
		          insort(result, elem, 0, null, cmp);
		          result.pop();
		          los = result[result.length - 1];
		        }
		      }
		      return result;
		    }
		    heapify(array, cmp);
		    _results = [];
		    for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {
		      _results.push(heappop(array, cmp));
		    }
		    return _results;
		  };

		  _siftdown = function(array, startpos, pos, cmp) {
		    var newitem, parent, parentpos;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    newitem = array[pos];
		    while (pos > startpos) {
		      parentpos = (pos - 1) >> 1;
		      parent = array[parentpos];
		      if (cmp(newitem, parent) < 0) {
		        array[pos] = parent;
		        pos = parentpos;
		        continue;
		      }
		      break;
		    }
		    return array[pos] = newitem;
		  };

		  _siftup = function(array, pos, cmp) {
		    var childpos, endpos, newitem, rightpos, startpos;
		    if (cmp == null) {
		      cmp = defaultCmp;
		    }
		    endpos = array.length;
		    startpos = pos;
		    newitem = array[pos];
		    childpos = 2 * pos + 1;
		    while (childpos < endpos) {
		      rightpos = childpos + 1;
		      if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
		        childpos = rightpos;
		      }
		      array[pos] = array[childpos];
		      pos = childpos;
		      childpos = 2 * pos + 1;
		    }
		    array[pos] = newitem;
		    return _siftdown(array, startpos, pos, cmp);
		  };

		  Heap = (function() {
		    Heap.push = heappush;

		    Heap.pop = heappop;

		    Heap.replace = heapreplace;

		    Heap.pushpop = heappushpop;

		    Heap.heapify = heapify;

		    Heap.updateItem = updateItem;

		    Heap.nlargest = nlargest;

		    Heap.nsmallest = nsmallest;

		    function Heap(cmp) {
		      this.cmp = cmp != null ? cmp : defaultCmp;
		      this.nodes = [];
		    }

		    Heap.prototype.push = function(x) {
		      return heappush(this.nodes, x, this.cmp);
		    };

		    Heap.prototype.pop = function() {
		      return heappop(this.nodes, this.cmp);
		    };

		    Heap.prototype.peek = function() {
		      return this.nodes[0];
		    };

		    Heap.prototype.contains = function(x) {
		      return this.nodes.indexOf(x) !== -1;
		    };

		    Heap.prototype.replace = function(x) {
		      return heapreplace(this.nodes, x, this.cmp);
		    };

		    Heap.prototype.pushpop = function(x) {
		      return heappushpop(this.nodes, x, this.cmp);
		    };

		    Heap.prototype.heapify = function() {
		      return heapify(this.nodes, this.cmp);
		    };

		    Heap.prototype.updateItem = function(x) {
		      return updateItem(this.nodes, x, this.cmp);
		    };

		    Heap.prototype.clear = function() {
		      return this.nodes = [];
		    };

		    Heap.prototype.empty = function() {
		      return this.nodes.length === 0;
		    };

		    Heap.prototype.size = function() {
		      return this.nodes.length;
		    };

		    Heap.prototype.clone = function() {
		      var heap;
		      heap = new Heap();
		      heap.nodes = this.nodes.slice(0);
		      return heap;
		    };

		    Heap.prototype.toArray = function() {
		      return this.nodes.slice(0);
		    };

		    Heap.prototype.insert = Heap.prototype.push;

		    Heap.prototype.top = Heap.prototype.peek;

		    Heap.prototype.front = Heap.prototype.peek;

		    Heap.prototype.has = Heap.prototype.contains;

		    Heap.prototype.copy = Heap.prototype.clone;

		    return Heap;

		  })();

		  (function(root, factory) {
		    {
		      return module.exports = factory();
		    }
		  })(this, function() {
		    return Heap;
		  });

		}).call(heap$1); 
	} (heap$2));
	return heap$2.exports;
}

var heap;
var hasRequiredHeap;

function requireHeap () {
	if (hasRequiredHeap) return heap;
	hasRequiredHeap = 1;
	heap = requireHeap$1();
	return heap;
}

var heapExports = requireHeap();
var Heap = /*@__PURE__*/getDefaultExportFromCjs(heapExports);

var dijkstraDefaults = defaults$g({
  root: null,
  weight: function weight(edge) {
    return 1;
  },
  directed: false
});
var elesfn$u = {
  dijkstra: function dijkstra(options) {
    if (!plainObject(options)) {
      var args = arguments;
      options = {
        root: args[0],
        weight: args[1],
        directed: args[2]
      };
    }
    var _dijkstraDefaults = dijkstraDefaults(options),
      root = _dijkstraDefaults.root,
      weight = _dijkstraDefaults.weight,
      directed = _dijkstraDefaults.directed;
    var eles = this;
    var weightFn = weight;
    var source = string(root) ? this.filter(root)[0] : root[0];
    var dist = {};
    var prev = {};
    var knownDist = {};
    var _this$byGroup = this.byGroup(),
      nodes = _this$byGroup.nodes,
      edges = _this$byGroup.edges;
    edges.unmergeBy(function (ele) {
      return ele.isLoop();
    });
    var getDist = function getDist(node) {
      return dist[node.id()];
    };
    var setDist = function setDist(node, d) {
      dist[node.id()] = d;
      Q.updateItem(node);
    };
    var Q = new Heap(function (a, b) {
      return getDist(a) - getDist(b);
    });
    for (var i = 0; i < nodes.length; i++) {
      var node = nodes[i];
      dist[node.id()] = node.same(source) ? 0 : Infinity;
      Q.push(node);
    }
    var distBetween = function distBetween(u, v) {
      var uvs = (directed ? u.edgesTo(v) : u.edgesWith(v)).intersect(edges);
      var smallestDistance = Infinity;
      var smallestEdge;
      for (var _i = 0; _i < uvs.length; _i++) {
        var edge = uvs[_i];
        var _weight = weightFn(edge);
        if (_weight < smallestDistance || !smallestEdge) {
          smallestDistance = _weight;
          smallestEdge = edge;
        }
      }
      return {
        edge: smallestEdge,
        dist: smallestDistance
      };
    };
    while (Q.size() > 0) {
      var u = Q.pop();
      var smalletsDist = getDist(u);
      var uid = u.id();
      knownDist[uid] = smalletsDist;
      if (smalletsDist === Infinity) {
        continue;
      }
      var neighbors = u.neighborhood().intersect(nodes);
      for (var _i2 = 0; _i2 < neighbors.length; _i2++) {
        var v = neighbors[_i2];
        var vid = v.id();
        var vDist = distBetween(u, v);
        var alt = smalletsDist + vDist.dist;
        if (alt < getDist(v)) {
          setDist(v, alt);
          prev[vid] = {
            node: u,
            edge: vDist.edge
          };
        }
      } // for
    } // while

    return {
      distanceTo: function distanceTo(node) {
        var target = string(node) ? nodes.filter(node)[0] : node[0];
        return knownDist[target.id()];
      },
      pathTo: function pathTo(node) {
        var target = string(node) ? nodes.filter(node)[0] : node[0];
        var S = [];
        var u = target;
        var uid = u.id();
        if (target.length > 0) {
          S.unshift(target);
          while (prev[uid]) {
            var p = prev[uid];
            S.unshift(p.edge);
            S.unshift(p.node);
            u = p.node;
            uid = u.id();
          }
        }
        return eles.spawn(S);
      }
    };
  }
};

var elesfn$t = {
  // kruskal's algorithm (finds min spanning tree, assuming undirected graph)
  // implemented from pseudocode from wikipedia
  kruskal: function kruskal(weightFn) {
    weightFn = weightFn || function (edge) {
      return 1;
    };
    var _this$byGroup = this.byGroup(),
      nodes = _this$byGroup.nodes,
      edges = _this$byGroup.edges;
    var numNodes = nodes.length;
    var forest = new Array(numNodes);
    var A = nodes; // assumes byGroup() creates new collections that can be safely mutated

    var findSetIndex = function findSetIndex(ele) {
      for (var i = 0; i < forest.length; i++) {
        var eles = forest[i];
        if (eles.has(ele)) {
          return i;
        }
      }
    };

    // start with one forest per node
    for (var i = 0; i < numNodes; i++) {
      forest[i] = this.spawn(nodes[i]);
    }
    var S = edges.sort(function (a, b) {
      return weightFn(a) - weightFn(b);
    });
    for (var _i = 0; _i < S.length; _i++) {
      var edge = S[_i];
      var u = edge.source()[0];
      var v = edge.target()[0];
      var setUIndex = findSetIndex(u);
      var setVIndex = findSetIndex(v);
      var setU = forest[setUIndex];
      var setV = forest[setVIndex];
      if (setUIndex !== setVIndex) {
        A.merge(edge);

        // combine forests for u and v
        setU.merge(setV);
        forest.splice(setVIndex, 1);
      }
    }
    return A;
  }
};

var aStarDefaults = defaults$g({
  root: null,
  goal: null,
  weight: function weight(edge) {
    return 1;
  },
  heuristic: function heuristic(edge) {
    return 0;
  },
  directed: false
});
var elesfn$s = {
  // Implemented from pseudocode from wikipedia
  aStar: function aStar(options) {
    var cy = this.cy();
    var _aStarDefaults = aStarDefaults(options),
      root = _aStarDefaults.root,
      goal = _aStarDefaults.goal,
      heuristic = _aStarDefaults.heuristic,
      directed = _aStarDefaults.directed,
      weight = _aStarDefaults.weight;
    root = cy.collection(root)[0];
    goal = cy.collection(goal)[0];
    var sid = root.id();
    var tid = goal.id();
    var gScore = {};
    var fScore = {};
    var closedSetIds = {};
    var openSet = new Heap(function (a, b) {
      return fScore[a.id()] - fScore[b.id()];
    });
    var openSetIds = new Set$1();
    var cameFrom = {};
    var cameFromEdge = {};
    var addToOpenSet = function addToOpenSet(ele, id) {
      openSet.push(ele);
      openSetIds.add(id);
    };
    var cMin, cMinId;
    var popFromOpenSet = function popFromOpenSet() {
      cMin = openSet.pop();
      cMinId = cMin.id();
      openSetIds["delete"](cMinId);
    };
    var isInOpenSet = function isInOpenSet(id) {
      return openSetIds.has(id);
    };
    addToOpenSet(root, sid);
    gScore[sid] = 0;
    fScore[sid] = heuristic(root);

    // Counter
    var steps = 0;

    // Main loop
    while (openSet.size() > 0) {
      popFromOpenSet();
      steps++;

      // If we've found our goal, then we are done
      if (cMinId === tid) {
        var path = [];
        var pathNode = goal;
        var pathNodeId = tid;
        var pathEdge = cameFromEdge[pathNodeId];
        for (;;) {
          path.unshift(pathNode);
          if (pathEdge != null) {
            path.unshift(pathEdge);
          }
          pathNode = cameFrom[pathNodeId];
          if (pathNode == null) {
            break;
          }
          pathNodeId = pathNode.id();
          pathEdge = cameFromEdge[pathNodeId];
        }
        return {
          found: true,
          distance: gScore[cMinId],
          path: this.spawn(path),
          steps: steps
        };
      }

      // Add cMin to processed nodes
      closedSetIds[cMinId] = true;

      // Update scores for neighbors of cMin
      // Take into account if graph is directed or not
      var vwEdges = cMin._private.edges;
      for (var i = 0; i < vwEdges.length; i++) {
        var e = vwEdges[i];

        // edge must be in set of calling eles
        if (!this.hasElementWithId(e.id())) {
          continue;
        }

        // cMin must be the source of edge if directed
        if (directed && e.data('source') !== cMinId) {
          continue;
        }
        var wSrc = e.source();
        var wTgt = e.target();
        var w = wSrc.id() !== cMinId ? wSrc : wTgt;
        var wid = w.id();

        // node must be in set of calling eles
        if (!this.hasElementWithId(wid)) {
          continue;
        }

        // if node is in closedSet, ignore it
        if (closedSetIds[wid]) {
          continue;
        }

        // New tentative score for node w
        var tempScore = gScore[cMinId] + weight(e);

        // Update gScore for node w if:
        //   w not present in openSet
        // OR
        //   tentative gScore is less than previous value

        // w not in openSet
        if (!isInOpenSet(wid)) {
          gScore[wid] = tempScore;
          fScore[wid] = tempScore + heuristic(w);
          addToOpenSet(w, wid);
          cameFrom[wid] = cMin;
          cameFromEdge[wid] = e;
          continue;
        }

        // w already in openSet, but with greater gScore
        if (tempScore < gScore[wid]) {
          gScore[wid] = tempScore;
          fScore[wid] = tempScore + heuristic(w);
          cameFrom[wid] = cMin;
          cameFromEdge[wid] = e;
        }
      } // End of neighbors update
    } // End of main loop

    // If we've reached here, then we've not reached our goal
    return {
      found: false,
      distance: undefined,
      path: undefined,
      steps: steps
    };
  }
}; // elesfn

var floydWarshallDefaults = defaults$g({
  weight: function weight(edge) {
    return 1;
  },
  directed: false
});
var elesfn$r = {
  // Implemented from pseudocode from wikipedia
  floydWarshall: function floydWarshall(options) {
    var cy = this.cy();
    var _floydWarshallDefault = floydWarshallDefaults(options),
      weight = _floydWarshallDefault.weight,
      directed = _floydWarshallDefault.directed;
    var weightFn = weight;
    var _this$byGroup = this.byGroup(),
      nodes = _this$byGroup.nodes,
      edges = _this$byGroup.edges;
    var N = nodes.length;
    var Nsq = N * N;
    var indexOf = function indexOf(node) {
      return nodes.indexOf(node);
    };
    var atIndex = function atIndex(i) {
      return nodes[i];
    };

    // Initialize distance matrix
    var dist = new Array(Nsq);
    for (var n = 0; n < Nsq; n++) {
      var j = n % N;
      var i = (n - j) / N;
      if (i === j) {
        dist[n] = 0;
      } else {
        dist[n] = Infinity;
      }
    }

    // Initialize matrix used for path reconstruction
    // Initialize distance matrix
    var next = new Array(Nsq);
    var edgeNext = new Array(Nsq);

    // Process edges
    for (var _i = 0; _i < edges.length; _i++) {
      var edge = edges[_i];
      var src = edge.source()[0];
      var tgt = edge.target()[0];
      if (src === tgt) {
        continue;
      } // exclude loops

      var s = indexOf(src);
      var t = indexOf(tgt);
      var st = s * N + t; // source to target index
      var _weight = weightFn(edge);

      // Check if already process another edge between same 2 nodes
      if (dist[st] > _weight) {
        dist[st] = _weight;
        next[st] = t;
        edgeNext[st] = edge;
      }

      // If undirected graph, process 'reversed' edge
      if (!directed) {
        var ts = t * N + s; // target to source index

        if (!directed && dist[ts] > _weight) {
          dist[ts] = _weight;
          next[ts] = s;
          edgeNext[ts] = edge;
        }
      }
    }

    // Main loop
    for (var k = 0; k < N; k++) {
      for (var _i2 = 0; _i2 < N; _i2++) {
        var ik = _i2 * N + k;
        for (var _j = 0; _j < N; _j++) {
          var ij = _i2 * N + _j;
          var kj = k * N + _j;
          if (dist[ik] + dist[kj] < dist[ij]) {
            dist[ij] = dist[ik] + dist[kj];
            next[ij] = next[ik];
          }
        }
      }
    }
    var getArgEle = function getArgEle(ele) {
      return (string(ele) ? cy.filter(ele) : ele)[0];
    };
    var indexOfArgEle = function indexOfArgEle(ele) {
      return indexOf(getArgEle(ele));
    };
    var res = {
      distance: function distance(from, to) {
        var i = indexOfArgEle(from);
        var j = indexOfArgEle(to);
        return dist[i * N + j];
      },
      path: function path(from, to) {
        var i = indexOfArgEle(from);
        var j = indexOfArgEle(to);
        var fromNode = atIndex(i);
        if (i === j) {
          return fromNode.collection();
        }
        if (next[i * N + j] == null) {
          return cy.collection();
        }
        var path = cy.collection();
        var prev = i;
        var edge;
        path.merge(fromNode);
        while (i !== j) {
          prev = i;
          i = next[i * N + j];
          edge = edgeNext[prev * N + i];
          path.merge(edge);
          path.merge(atIndex(i));
        }
        return path;
      }
    };
    return res;
  } // floydWarshall
}; // elesfn

var bellmanFordDefaults = defaults$g({
  weight: function weight(edge) {
    return 1;
  },
  directed: false,
  root: null
});
var elesfn$q = {
  // Implemented from pseudocode from wikipedia
  bellmanFord: function bellmanFord(options) {
    var _this = this;
    var _bellmanFordDefaults = bellmanFordDefaults(options),
      weight = _bellmanFordDefaults.weight,
      directed = _bellmanFordDefaults.directed,
      root = _bellmanFordDefaults.root;
    var weightFn = weight;
    var eles = this;
    var cy = this.cy();
    var _this$byGroup = this.byGroup(),
      edges = _this$byGroup.edges,
      nodes = _this$byGroup.nodes;
    var numNodes = nodes.length;
    var infoMap = new Map$1();
    var hasNegativeWeightCycle = false;
    var negativeWeightCycles = [];
    root = cy.collection(root)[0]; // in case selector passed

    edges.unmergeBy(function (edge) {
      return edge.isLoop();
    });
    var numEdges = edges.length;
    var getInfo = function getInfo(node) {
      var obj = infoMap.get(node.id());
      if (!obj) {
        obj = {};
        infoMap.set(node.id(), obj);
      }
      return obj;
    };
    var getNodeFromTo = function getNodeFromTo(to) {
      return (string(to) ? cy.$(to) : to)[0];
    };
    var distanceTo = function distanceTo(to) {
      return getInfo(getNodeFromTo(to)).dist;
    };
    var pathTo = function pathTo(to) {
      var thisStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;
      var end = getNodeFromTo(to);
      var path = [];
      var node = end;
      for (;;) {
        if (node == null) {
          return _this.spawn();
        }
        var _getInfo = getInfo(node),
          edge = _getInfo.edge,
          pred = _getInfo.pred;
        path.unshift(node[0]);
        if (node.same(thisStart) && path.length > 0) {
          break;
        }
        if (edge != null) {
          path.unshift(edge);
        }
        node = pred;
      }
      return eles.spawn(path);
    };

    // Initializations { dist, pred, edge }
    for (var i = 0; i < numNodes; i++) {
      var node = nodes[i];
      var info = getInfo(node);
      if (node.same(root)) {
        info.dist = 0;
      } else {
        info.dist = Infinity;
      }
      info.pred = null;
      info.edge = null;
    }

    // Edges relaxation
    var replacedEdge = false;
    var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {
      var dist = info1.dist + weight;
      if (dist < info2.dist && !edge.same(info1.edge)) {
        info2.dist = dist;
        info2.pred = node1;
        info2.edge = edge;
        replacedEdge = true;
      }
    };
    for (var _i = 1; _i < numNodes; _i++) {
      replacedEdge = false;
      for (var e = 0; e < numEdges; e++) {
        var edge = edges[e];
        var src = edge.source();
        var tgt = edge.target();
        var _weight = weightFn(edge);
        var srcInfo = getInfo(src);
        var tgtInfo = getInfo(tgt);
        checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight);

        // If undirected graph, we need to take into account the 'reverse' edge
        if (!directed) {
          checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);
        }
      }
      if (!replacedEdge) {
        break;
      }
    }
    if (replacedEdge) {
      // Check for negative weight cycles
      var negativeWeightCycleIds = [];
      for (var _e = 0; _e < numEdges; _e++) {
        var _edge = edges[_e];
        var _src = _edge.source();
        var _tgt = _edge.target();
        var _weight2 = weightFn(_edge);
        var srcDist = getInfo(_src).dist;
        var tgtDist = getInfo(_tgt).dist;
        if (srcDist + _weight2 < tgtDist || !directed && tgtDist + _weight2 < srcDist) {
          if (!hasNegativeWeightCycle) {
            warn('Graph contains a negative weight cycle for Bellman-Ford');
            hasNegativeWeightCycle = true;
          }
          if (options.findNegativeWeightCycles !== false) {
            var negativeNodes = [];
            if (srcDist + _weight2 < tgtDist) {
              negativeNodes.push(_src);
            }
            if (!directed && tgtDist + _weight2 < srcDist) {
              negativeNodes.push(_tgt);
            }
            var numNegativeNodes = negativeNodes.length;
            for (var n = 0; n < numNegativeNodes; n++) {
              var start = negativeNodes[n];
              var cycle = [start];
              cycle.push(getInfo(start).edge);
              var _node = getInfo(start).pred;
              while (cycle.indexOf(_node) === -1) {
                cycle.push(_node);
                cycle.push(getInfo(_node).edge);
                _node = getInfo(_node).pred;
              }
              cycle = cycle.slice(cycle.indexOf(_node));
              var smallestId = cycle[0].id();
              var smallestIndex = 0;
              for (var c = 2; c < cycle.length; c += 2) {
                if (cycle[c].id() < smallestId) {
                  smallestId = cycle[c].id();
                  smallestIndex = c;
                }
              }
              cycle = cycle.slice(smallestIndex).concat(cycle.slice(0, smallestIndex));
              cycle.push(cycle[0]);
              var cycleId = cycle.map(function (el) {
                return el.id();
              }).join(",");
              if (negativeWeightCycleIds.indexOf(cycleId) === -1) {
                negativeWeightCycles.push(eles.spawn(cycle));
                negativeWeightCycleIds.push(cycleId);
              }
            }
          } else {
            break;
          }
        }
      }
    }
    return {
      distanceTo: distanceTo,
      pathTo: pathTo,
      hasNegativeWeightCycle: hasNegativeWeightCycle,
      negativeWeightCycles: negativeWeightCycles
    };
  } // bellmanFord
}; // elesfn

var sqrt2 = Math.sqrt(2);

// Function which colapses 2 (meta) nodes into one
// Updates the remaining edge lists
// Receives as a paramater the edge which causes the collapse
var collapse = function collapse(edgeIndex, nodeMap, remainingEdges) {
  if (remainingEdges.length === 0) {
    error("Karger-Stein must be run on a connected (sub)graph");
  }
  var edgeInfo = remainingEdges[edgeIndex];
  var sourceIn = edgeInfo[1];
  var targetIn = edgeInfo[2];
  var partition1 = nodeMap[sourceIn];
  var partition2 = nodeMap[targetIn];
  var newEdges = remainingEdges; // re-use array

  // Delete all edges between partition1 and partition2
  for (var i = newEdges.length - 1; i >= 0; i--) {
    var edge = newEdges[i];
    var src = edge[1];
    var tgt = edge[2];
    if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {
      newEdges.splice(i, 1);
    }
  }

  // All edges pointing to partition2 should now point to partition1
  for (var _i = 0; _i < newEdges.length; _i++) {
    var _edge = newEdges[_i];
    if (_edge[1] === partition2) {
      // Check source
      newEdges[_i] = _edge.slice(); // copy
      newEdges[_i][1] = partition1;
    } else if (_edge[2] === partition2) {
      // Check target
      newEdges[_i] = _edge.slice(); // copy
      newEdges[_i][2] = partition1;
    }
  }

  // Move all nodes from partition2 to partition1
  for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {
    if (nodeMap[_i2] === partition2) {
      nodeMap[_i2] = partition1;
    }
  }
  return newEdges;
};

// Contracts a graph until we reach a certain number of meta nodes
var contractUntil = function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {
  while (size > sizeLimit) {
    // Choose an edge randomly
    var edgeIndex = Math.floor(Math.random() * remainingEdges.length);

    // Collapse graph based on edge
    remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);
    size--;
  }
  return remainingEdges;
};
var elesfn$p = {
  // Computes the minimum cut of an undirected graph
  // Returns the correct answer with high probability
  kargerStein: function kargerStein() {
    var _this = this;
    var _this$byGroup = this.byGroup(),
      nodes = _this$byGroup.nodes,
      edges = _this$byGroup.edges;
    edges.unmergeBy(function (edge) {
      return edge.isLoop();
    });
    var numNodes = nodes.length;
    var numEdges = edges.length;
    var numIter = Math.ceil(Math.pow(Math.log(numNodes) / Math.LN2, 2));
    var stopSize = Math.floor(numNodes / sqrt2);
    if (numNodes < 2) {
      error('At least 2 nodes are required for Karger-Stein algorithm');
      return undefined;
    }

    // Now store edge destination as indexes
    // Format for each edge (edge index, source node index, target node index)
    var edgeIndexes = [];
    for (var i = 0; i < numEdges; i++) {
      var e = edges[i];
      edgeIndexes.push([i, nodes.indexOf(e.source()), nodes.indexOf(e.target())]);
    }

    // We will store the best cut found here
    var minCutSize = Infinity;
    var minCutEdgeIndexes = [];
    var minCutNodeMap = new Array(numNodes);

    // Initial meta node partition
    var metaNodeMap = new Array(numNodes);
    var metaNodeMap2 = new Array(numNodes);
    var copyNodesMap = function copyNodesMap(from, to) {
      for (var _i3 = 0; _i3 < numNodes; _i3++) {
        to[_i3] = from[_i3];
      }
    };

    // Main loop
    for (var iter = 0; iter <= numIter; iter++) {
      // Reset meta node partition
      for (var _i4 = 0; _i4 < numNodes; _i4++) {
        metaNodeMap[_i4] = _i4;
      }

      // Contract until stop point (stopSize nodes)
      var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);
      var edgesState2 = edgesState.slice(); // copy

      // Create a copy of the colapsed nodes state
      copyNodesMap(metaNodeMap, metaNodeMap2);

      // Run 2 iterations starting in the stop state
      var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);
      var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2);

      // Is any of the 2 results the best cut so far?
      if (res1.length <= res2.length && res1.length < minCutSize) {
        minCutSize = res1.length;
        minCutEdgeIndexes = res1;
        copyNodesMap(metaNodeMap, minCutNodeMap);
      } else if (res2.length <= res1.length && res2.length < minCutSize) {
        minCutSize = res2.length;
        minCutEdgeIndexes = res2;
        copyNodesMap(metaNodeMap2, minCutNodeMap);
      }
    } // end of main loop

    // Construct result
    var cut = this.spawn(minCutEdgeIndexes.map(function (e) {
      return edges[e[0]];
    }));
    var partition1 = this.spawn();
    var partition2 = this.spawn();

    // traverse metaNodeMap for best cut
    var witnessNodePartition = minCutNodeMap[0];
    for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {
      var partitionId = minCutNodeMap[_i5];
      var node = nodes[_i5];
      if (partitionId === witnessNodePartition) {
        partition1.merge(node);
      } else {
        partition2.merge(node);
      }
    }

    // construct components corresponding to each disjoint subset of nodes
    var constructComponent = function constructComponent(subset) {
      var component = _this.spawn();
      subset.forEach(function (node) {
        component.merge(node);
        node.connectedEdges().forEach(function (edge) {
          // ensure edge is within calling collection and edge is not in cut
          if (_this.contains(edge) && !cut.contains(edge)) {
            component.merge(edge);
          }
        });
      });
      return component;
    };
    var components = [constructComponent(partition1), constructComponent(partition2)];
    var ret = {
      cut: cut,
      components: components,
      // n.b. partitions are included to be compatible with the old api spec
      // (could be removed in a future major version)
      partition1: partition1,
      partition2: partition2
    };
    return ret;
  }
}; // elesfn

var _Math$hypot;
var copyPosition = function copyPosition(p) {
  return {
    x: p.x,
    y: p.y
  };
};
var modelToRenderedPosition$1 = function modelToRenderedPosition(p, zoom, pan) {
  return {
    x: p.x * zoom + pan.x,
    y: p.y * zoom + pan.y
  };
};
var renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {
  return {
    x: (p.x - pan.x) / zoom,
    y: (p.y - pan.y) / zoom
  };
};
var array2point = function array2point(arr) {
  return {
    x: arr[0],
    y: arr[1]
  };
};
var min = function min(arr) {
  var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  var min = Infinity;
  for (var i = begin; i < end; i++) {
    var val = arr[i];
    if (isFinite(val)) {
      min = Math.min(val, min);
    }
  }
  return min;
};
var max = function max(arr) {
  var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  var max = -Infinity;
  for (var i = begin; i < end; i++) {
    var val = arr[i];
    if (isFinite(val)) {
      max = Math.max(val, max);
    }
  }
  return max;
};
var mean = function mean(arr) {
  var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  var total = 0;
  var n = 0;
  for (var i = begin; i < end; i++) {
    var val = arr[i];
    if (isFinite(val)) {
      total += val;
      n++;
    }
  }
  return total / n;
};
var median = function median(arr) {
  var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  var copy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var sort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  var includeHoles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  if (copy) {
    arr = arr.slice(begin, end);
  } else {
    if (end < arr.length) {
      arr.splice(end, arr.length - end);
    }
    if (begin > 0) {
      arr.splice(0, begin);
    }
  }

  // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start
  var off = 0; // offset from non-finite values
  for (var i = arr.length - 1; i >= 0; i--) {
    var v = arr[i];
    if (includeHoles) {
      if (!isFinite(v)) {
        arr[i] = -Infinity;
        off++;
      }
    } else {
      // just remove it if we don't want to consider holes
      arr.splice(i, 1);
    }
  }
  if (sort) {
    arr.sort(function (a, b) {
      return a - b;
    }); // requires copy = true if you don't want to change the orig
  }
  var len = arr.length;
  var mid = Math.floor(len / 2);
  if (len % 2 !== 0) {
    return arr[mid + 1 + off];
  } else {
    return (arr[mid - 1 + off] + arr[mid + off]) / 2;
  }
};
var deg2rad = function deg2rad(deg) {
  return Math.PI * deg / 180;
};
var getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {
  return Math.atan2(dispY, dispX) - Math.PI / 2;
};
var log2 = Math.log2 || function (n) {
  return Math.log(n) / Math.log(2);
};
var signum = function signum(x) {
  if (x > 0) {
    return 1;
  } else if (x < 0) {
    return -1;
  } else {
    return 0;
  }
};
var dist = function dist(p1, p2) {
  return Math.sqrt(sqdist(p1, p2));
};
var sqdist = function sqdist(p1, p2) {
  var dx = p2.x - p1.x;
  var dy = p2.y - p1.y;
  return dx * dx + dy * dy;
};
var inPlaceSumNormalize = function inPlaceSumNormalize(v) {
  var length = v.length;

  // First, get sum of all elements
  var total = 0;
  for (var i = 0; i < length; i++) {
    total += v[i];
  }

  // Now, divide each by the sum of all elements
  for (var _i = 0; _i < length; _i++) {
    v[_i] = v[_i] / total;
  }
  return v;
};

// from http://en.wikipedia.org/wiki/Bézier_curve#Quadratic_curves
var qbezierAt = function qbezierAt(p0, p1, p2, t) {
  return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;
};
var qbezierPtAt = function qbezierPtAt(p0, p1, p2, t) {
  return {
    x: qbezierAt(p0.x, p1.x, p2.x, t),
    y: qbezierAt(p0.y, p1.y, p2.y, t)
  };
};
var lineAt = function lineAt(p0, p1, t, d) {
  var vec = {
    x: p1.x - p0.x,
    y: p1.y - p0.y
  };
  var vecDist = dist(p0, p1);
  var normVec = {
    x: vec.x / vecDist,
    y: vec.y / vecDist
  };
  t = t == null ? 0 : t;
  d = d != null ? d : t * vecDist;
  return {
    x: p0.x + normVec.x * d,
    y: p0.y + normVec.y * d
  };
};
var bound = function bound(min, val, max) {
  return Math.max(min, Math.min(max, val));
};

// makes a full bb (x1, y1, x2, y2, w, h) from implicit params
var makeBoundingBox = function makeBoundingBox(bb) {
  if (bb == null) {
    return {
      x1: Infinity,
      y1: Infinity,
      x2: -Infinity,
      y2: -Infinity,
      w: 0,
      h: 0
    };
  } else if (bb.x1 != null && bb.y1 != null) {
    if (bb.x2 != null && bb.y2 != null && bb.x2 >= bb.x1 && bb.y2 >= bb.y1) {
      return {
        x1: bb.x1,
        y1: bb.y1,
        x2: bb.x2,
        y2: bb.y2,
        w: bb.x2 - bb.x1,
        h: bb.y2 - bb.y1
      };
    } else if (bb.w != null && bb.h != null && bb.w >= 0 && bb.h >= 0) {
      return {
        x1: bb.x1,
        y1: bb.y1,
        x2: bb.x1 + bb.w,
        y2: bb.y1 + bb.h,
        w: bb.w,
        h: bb.h
      };
    }
  }
};
var copyBoundingBox = function copyBoundingBox(bb) {
  return {
    x1: bb.x1,
    x2: bb.x2,
    w: bb.w,
    y1: bb.y1,
    y2: bb.y2,
    h: bb.h
  };
};
var clearBoundingBox = function clearBoundingBox(bb) {
  bb.x1 = Infinity;
  bb.y1 = Infinity;
  bb.x2 = -Infinity;
  bb.y2 = -Infinity;
  bb.w = 0;
  bb.h = 0;
};
var updateBoundingBox = function updateBoundingBox(bb1, bb2) {
  // update bb1 with bb2 bounds

  bb1.x1 = Math.min(bb1.x1, bb2.x1);
  bb1.x2 = Math.max(bb1.x2, bb2.x2);
  bb1.w = bb1.x2 - bb1.x1;
  bb1.y1 = Math.min(bb1.y1, bb2.y1);
  bb1.y2 = Math.max(bb1.y2, bb2.y2);
  bb1.h = bb1.y2 - bb1.y1;
};
var expandBoundingBoxByPoint = function expandBoundingBoxByPoint(bb, x, y) {
  bb.x1 = Math.min(bb.x1, x);
  bb.x2 = Math.max(bb.x2, x);
  bb.w = bb.x2 - bb.x1;
  bb.y1 = Math.min(bb.y1, y);
  bb.y2 = Math.max(bb.y2, y);
  bb.h = bb.y2 - bb.y1;
};
var expandBoundingBox = function expandBoundingBox(bb) {
  var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  bb.x1 -= padding;
  bb.x2 += padding;
  bb.y1 -= padding;
  bb.y2 += padding;
  bb.w = bb.x2 - bb.x1;
  bb.h = bb.y2 - bb.y1;
  return bb;
};
var expandBoundingBoxSides = function expandBoundingBoxSides(bb) {
  var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];
  var top, right, bottom, left;
  if (padding.length === 1) {
    top = right = bottom = left = padding[0];
  } else if (padding.length === 2) {
    top = bottom = padding[0];
    left = right = padding[1];
  } else if (padding.length === 4) {
    var _padding = _slicedToArray(padding, 4);
    top = _padding[0];
    right = _padding[1];
    bottom = _padding[2];
    left = _padding[3];
  }
  bb.x1 -= left;
  bb.x2 += right;
  bb.y1 -= top;
  bb.y2 += bottom;
  bb.w = bb.x2 - bb.x1;
  bb.h = bb.y2 - bb.y1;
  return bb;
};

// assign the values of bb2 into bb1
var assignBoundingBox = function assignBoundingBox(bb1, bb2) {
  bb1.x1 = bb2.x1;
  bb1.y1 = bb2.y1;
  bb1.x2 = bb2.x2;
  bb1.y2 = bb2.y2;
  bb1.w = bb1.x2 - bb1.x1;
  bb1.h = bb1.y2 - bb1.y1;
};
var boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {
  // case: one bb to right of other
  if (bb1.x1 > bb2.x2) {
    return false;
  }
  if (bb2.x1 > bb1.x2) {
    return false;
  }

  // case: one bb to left of other
  if (bb1.x2 < bb2.x1) {
    return false;
  }
  if (bb2.x2 < bb1.x1) {
    return false;
  }

  // case: one bb above other
  if (bb1.y2 < bb2.y1) {
    return false;
  }
  if (bb2.y2 < bb1.y1) {
    return false;
  }

  // case: one bb below other
  if (bb1.y1 > bb2.y2) {
    return false;
  }
  if (bb2.y1 > bb1.y2) {
    return false;
  }

  // otherwise, must have some overlap
  return true;
};
var inBoundingBox = function inBoundingBox(bb, x, y) {
  return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;
};
var pointInBoundingBox = function pointInBoundingBox(bb, pt) {
  return inBoundingBox(bb, pt.x, pt.y);
};
var boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {
  return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);
};
var hypot = (_Math$hypot = Math.hypot) !== null && _Math$hypot !== undefined ? _Math$hypot : function (x, y) {
  return Math.sqrt(x * x + y * y);
};
function inflatePolygon(polygon, d) {
  if (polygon.length < 3) {
    throw new Error('Need at least 3 vertices');
  }
  // Helpers
  var add = function add(a, b) {
    return {
      x: a.x + b.x,
      y: a.y + b.y
    };
  };
  var sub = function sub(a, b) {
    return {
      x: a.x - b.x,
      y: a.y - b.y
    };
  };
  var scale = function scale(v, s) {
    return {
      x: v.x * s,
      y: v.y * s
    };
  };
  var cross = function cross(u, v) {
    return u.x * v.y - u.y * v.x;
  };
  var normalize = function normalize(v) {
    var len = hypot(v.x, v.y);
    return len === 0 ? {
      x: 0,
      y: 0
    } : {
      x: v.x / len,
      y: v.y / len
    };
  };
  // Signed area (positive = CCW)
  var signedArea = function signedArea(pts) {
    var A = 0;
    for (var i = 0; i < pts.length; i++) {
      var p = pts[i],
        q = pts[(i + 1) % pts.length];
      A += p.x * q.y - q.x * p.y;
    }
    return A / 2;
  };
  // Line–line intersection (infinite lines)
  var intersectLines = function intersectLines(p1, p2, p3, p4) {
    var r = sub(p2, p1);
    var s = sub(p4, p3);
    var denom = cross(r, s);
    if (Math.abs(denom) < 1e-9) {
      // Parallel or nearly so — fallback to midpoint
      return add(p1, scale(r, 0.5));
    }
    var t = cross(sub(p3, p1), s) / denom;
    return add(p1, scale(r, t));
  };

  // Make a shallow copy and enforce CCW
  var pts = polygon.map(function (p) {
    return {
      x: p.x,
      y: p.y
    };
  });
  if (signedArea(pts) < 0) pts.reverse();
  var n = pts.length;
  // Compute outward normals for each edge
  var normals = [];
  for (var i = 0; i < n; i++) {
    var p = pts[i],
      q = pts[(i + 1) % n];
    var edge = sub(q, p);
    // For CCW polygon, inward normal = (-edge.y, edge.x)
    // so outward normal = (edge.y, -edge.x)
    var out = normalize({
      x: edge.y,
      y: -edge.x
    });
    normals.push(out);
  }

  // Build offset edges
  var offsetEdges = normals.map(function (nrm, i) {
    var p1 = add(pts[i], scale(nrm, d));
    var p2 = add(pts[(i + 1) % n], scale(nrm, d));
    return {
      p1: p1,
      p2: p2
    };
  });

  // Intersect consecutive offset edges
  var inflated = [];
  for (var _i2 = 0; _i2 < n; _i2++) {
    var prevEdge = offsetEdges[(_i2 - 1 + n) % n];
    var currEdge = offsetEdges[_i2];
    var ip = intersectLines(prevEdge.p1, prevEdge.p2, currEdge.p1, currEdge.p2);
    inflated.push(ip);
  }
  return inflated;
}
function miterBox(pts, centerX, centerY, width, height, strokeWidth) {
  var tpts = transformPoints(pts, centerX, centerY, width, height);
  var offsetPoints = inflatePolygon(tpts, strokeWidth);
  var bb = makeBoundingBox();
  offsetPoints.forEach(function (pt) {
    return expandBoundingBoxByPoint(bb, pt.x, pt.y);
  });
  return bb;
}
var roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {
  var radius = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'auto';
  var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  var halfWidth = width / 2;
  var halfHeight = height / 2;
  cornerRadius = Math.min(cornerRadius, halfWidth, halfHeight);
  var doWidth = cornerRadius !== halfWidth,
    doHeight = cornerRadius !== halfHeight;

  // Check intersections with straight line segments
  var straightLineIntersections;

  // Top segment, left to right
  if (doWidth) {
    var topStartX = nodeX - halfWidth + cornerRadius - padding;
    var topStartY = nodeY - halfHeight - padding;
    var topEndX = nodeX + halfWidth - cornerRadius + padding;
    var topEndY = topStartY;
    straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
    if (straightLineIntersections.length > 0) {
      return straightLineIntersections;
    }
  }

  // Right segment, top to bottom
  if (doHeight) {
    var rightStartX = nodeX + halfWidth + padding;
    var rightStartY = nodeY - halfHeight + cornerRadius - padding;
    var rightEndX = rightStartX;
    var rightEndY = nodeY + halfHeight - cornerRadius + padding;
    straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, rightStartX, rightStartY, rightEndX, rightEndY, false);
    if (straightLineIntersections.length > 0) {
      return straightLineIntersections;
    }
  }

  // Bottom segment, left to right
  if (doWidth) {
    var bottomStartX = nodeX - halfWidth + cornerRadius - padding;
    var bottomStartY = nodeY + halfHeight + padding;
    var bottomEndX = nodeX + halfWidth - cornerRadius + padding;
    var bottomEndY = bottomStartY;
    straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, bottomStartX, bottomStartY, bottomEndX, bottomEndY, false);
    if (straightLineIntersections.length > 0) {
      return straightLineIntersections;
    }
  }

  // Left segment, top to bottom
  if (doHeight) {
    var leftStartX = nodeX - halfWidth - padding;
    var leftStartY = nodeY - halfHeight + cornerRadius - padding;
    var leftEndX = leftStartX;
    var leftEndY = nodeY + halfHeight - cornerRadius + padding;
    straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, leftStartX, leftStartY, leftEndX, leftEndY, false);
    if (straightLineIntersections.length > 0) {
      return straightLineIntersections;
    }
  }

  // Check intersections with arc segments
  var arcIntersections;

  // Top Left
  {
    var topLeftCenterX = nodeX - halfWidth + cornerRadius;
    var topLeftCenterY = nodeY - halfHeight + cornerRadius;
    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding);

    // Ensure the intersection is on the desired quarter of the circle
    if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {
      return [arcIntersections[0], arcIntersections[1]];
    }
  }

  // Top Right
  {
    var topRightCenterX = nodeX + halfWidth - cornerRadius;
    var topRightCenterY = nodeY - halfHeight + cornerRadius;
    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding);

    // Ensure the intersection is on the desired quarter of the circle
    if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {
      return [arcIntersections[0], arcIntersections[1]];
    }
  }

  // Bottom Right
  {
    var bottomRightCenterX = nodeX + halfWidth - cornerRadius;
    var bottomRightCenterY = nodeY + halfHeight - cornerRadius;
    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding);

    // Ensure the intersection is on the desired quarter of the circle
    if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {
      return [arcIntersections[0], arcIntersections[1]];
    }
  }

  // Bottom Left
  {
    var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;
    var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;
    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding);

    // Ensure the intersection is on the desired quarter of the circle
    if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {
      return [arcIntersections[0], arcIntersections[1]];
    }
  }
  return []; // if nothing
};
var inLineVicinity = function inLineVicinity(x, y, lx1, ly1, lx2, ly2, tolerance) {
  var t = tolerance;
  var x1 = Math.min(lx1, lx2);
  var x2 = Math.max(lx1, lx2);
  var y1 = Math.min(ly1, ly2);
  var y2 = Math.max(ly1, ly2);
  return x1 - t <= x && x <= x2 + t && y1 - t <= y && y <= y2 + t;
};
var inBezierVicinity = function inBezierVicinity(x, y, x1, y1, x2, y2, x3, y3, tolerance) {
  var bb = {
    x1: Math.min(x1, x3, x2) - tolerance,
    x2: Math.max(x1, x3, x2) + tolerance,
    y1: Math.min(y1, y3, y2) - tolerance,
    y2: Math.max(y1, y3, y2) + tolerance
  };

  // if outside the rough bounding box for the bezier, then it can't be a hit
  if (x < bb.x1 || x > bb.x2 || y < bb.y1 || y > bb.y2) {
    // console.log('bezier out of rough bb')
    return false;
  } else {
    // console.log('do more expensive check');
    return true;
  }
};
var solveQuadratic = function solveQuadratic(a, b, c, val) {
  c -= val;
  var r = b * b - 4 * a * c;
  if (r < 0) {
    return [];
  }
  var sqrtR = Math.sqrt(r);
  var denom = 2 * a;
  var root1 = (-b + sqrtR) / denom;
  var root2 = (-b - sqrtR) / denom;
  return [root1, root2];
};
var solveCubic = function solveCubic(a, b, c, d, result) {
  // Solves a cubic function, returns root in form [r1, i1, r2, i2, r3, i3], where
  // r is the real component, i is the imaginary component

  // An implementation of the Cardano method from the year 1545
  // http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots

  var epsilon = 0.00001;

  // avoid division by zero while keeping the overall expression close in value
  if (a === 0) {
    a = epsilon;
  }
  b /= a;
  c /= a;
  d /= a;
  var discriminant, q, r, dum1, s, t, term1, r13;
  q = (3.0 * c - b * b) / 9.0;
  r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b));
  r /= 54.0;
  discriminant = q * q * q + r * r;
  result[1] = 0;
  term1 = b / 3.0;
  if (discriminant > 0) {
    s = r + Math.sqrt(discriminant);
    s = s < 0 ? -Math.pow(-s, 1.0 / 3.0) : Math.pow(s, 1.0 / 3.0);
    t = r - Math.sqrt(discriminant);
    t = t < 0 ? -Math.pow(-t, 1.0 / 3.0) : Math.pow(t, 1.0 / 3.0);
    result[0] = -term1 + s + t;
    term1 += (s + t) / 2.0;
    result[4] = result[2] = -term1;
    term1 = Math.sqrt(3.0) * (-t + s) / 2;
    result[3] = term1;
    result[5] = -term1;
    return;
  }
  result[5] = result[3] = 0;
  if (discriminant === 0) {
    r13 = r < 0 ? -Math.pow(-r, 1.0 / 3.0) : Math.pow(r, 1.0 / 3.0);
    result[0] = -term1 + 2.0 * r13;
    result[4] = result[2] = -(r13 + term1);
    return;
  }
  q = -q;
  dum1 = q * q * q;
  dum1 = Math.acos(r / Math.sqrt(dum1));
  r13 = 2.0 * Math.sqrt(q);
  result[0] = -term1 + r13 * Math.cos(dum1 / 3.0);
  result[2] = -term1 + r13 * Math.cos((dum1 + 2.0 * Math.PI) / 3.0);
  result[4] = -term1 + r13 * Math.cos((dum1 + 4.0 * Math.PI) / 3.0);
  return;
};
var sqdistToQuadraticBezier = function sqdistToQuadraticBezier(x, y, x1, y1, x2, y2, x3, y3) {
  // Find minimum distance by using the minimum of the distance
  // function between the given point and the curve

  // This gives the coefficients of the resulting cubic equation
  // whose roots tell us where a possible minimum is
  // (Coefficients are divided by 4)

  var a = 1.0 * x1 * x1 - 4 * x1 * x2 + 2 * x1 * x3 + 4 * x2 * x2 - 4 * x2 * x3 + x3 * x3 + y1 * y1 - 4 * y1 * y2 + 2 * y1 * y3 + 4 * y2 * y2 - 4 * y2 * y3 + y3 * y3;
  var b = 1.0 * 9 * x1 * x2 - 3 * x1 * x1 - 3 * x1 * x3 - 6 * x2 * x2 + 3 * x2 * x3 + 9 * y1 * y2 - 3 * y1 * y1 - 3 * y1 * y3 - 6 * y2 * y2 + 3 * y2 * y3;
  var c = 1.0 * 3 * x1 * x1 - 6 * x1 * x2 + x1 * x3 - x1 * x + 2 * x2 * x2 + 2 * x2 * x - x3 * x + 3 * y1 * y1 - 6 * y1 * y2 + y1 * y3 - y1 * y + 2 * y2 * y2 + 2 * y2 * y - y3 * y;
  var d = 1.0 * x1 * x2 - x1 * x1 + x1 * x - x2 * x + y1 * y2 - y1 * y1 + y1 * y - y2 * y;

  // debug("coefficients: " + a / a + ", " + b / a + ", " + c / a + ", " + d / a);

  var roots = [];

  // Use the cubic solving algorithm
  solveCubic(a, b, c, d, roots);
  var zeroThreshold = 0.0000001;
  var params = [];
  for (var index = 0; index < 6; index += 2) {
    if (Math.abs(roots[index + 1]) < zeroThreshold && roots[index] >= 0 && roots[index] <= 1.0) {
      params.push(roots[index]);
    }
  }
  params.push(1.0);
  params.push(0.0);
  var minDistanceSquared = -1;
  var curX, curY, distSquared;
  for (var i = 0; i < params.length; i++) {
    curX = Math.pow(1.0 - params[i], 2.0) * x1 + 2.0 * (1 - params[i]) * params[i] * x2 + params[i] * params[i] * x3;
    curY = Math.pow(1 - params[i], 2.0) * y1 + 2 * (1.0 - params[i]) * params[i] * y2 + params[i] * params[i] * y3;
    distSquared = Math.pow(curX - x, 2) + Math.pow(curY - y, 2);
    // debug('distance for param ' + params[i] + ": " + Math.sqrt(distSquared));
    if (minDistanceSquared >= 0) {
      if (distSquared < minDistanceSquared) {
        minDistanceSquared = distSquared;
      }
    } else {
      minDistanceSquared = distSquared;
    }
  }
  return minDistanceSquared;
};
var sqdistToFiniteLine = function sqdistToFiniteLine(x, y, x1, y1, x2, y2) {
  var offset = [x - x1, y - y1];
  var line = [x2 - x1, y2 - y1];
  var lineSq = line[0] * line[0] + line[1] * line[1];
  var hypSq = offset[0] * offset[0] + offset[1] * offset[1];
  var dotProduct = offset[0] * line[0] + offset[1] * line[1];
  var adjSq = dotProduct * dotProduct / lineSq;
  if (dotProduct < 0) {
    return hypSq;
  }
  if (adjSq > lineSq) {
    return (x - x2) * (x - x2) + (y - y2) * (y - y2);
  }
  return hypSq - adjSq;
};
var pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {
  var x1, y1, x2, y2;
  var y3;

  // Intersect with vertical line through (x, y)
  var up = 0;
  // let down = 0;
  for (var i = 0; i < points.length / 2; i++) {
    x1 = points[i * 2];
    y1 = points[i * 2 + 1];
    if (i + 1 < points.length / 2) {
      x2 = points[(i + 1) * 2];
      y2 = points[(i + 1) * 2 + 1];
    } else {
      x2 = points[(i + 1 - points.length / 2) * 2];
      y2 = points[(i + 1 - points.length / 2) * 2 + 1];
    }
    if (x1 == x && x2 == x) ; else if (x1 >= x && x >= x2 || x1 <= x && x <= x2) {
      y3 = (x - x1) / (x2 - x1) * (y2 - y1) + y1;
      if (y3 > y) {
        up++;
      }

      // if( y3 < y ){
      // down++;
      // }
    } else {
      continue;
    }
  }
  if (up % 2 === 0) {
    return false;
  } else {
    return true;
  }
};
var pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {
  var transformedPoints = new Array(basePoints.length);

  // Gives negative angle
  var angle;
  if (direction[0] != null) {
    angle = Math.atan(direction[1] / direction[0]);
    if (direction[0] < 0) {
      angle = angle + Math.PI / 2;
    } else {
      angle = -angle - Math.PI / 2;
    }
  } else {
    angle = direction;
  }
  var cos = Math.cos(-angle);
  var sin = Math.sin(-angle);

  //    console.log("base: " + basePoints);
  for (var i = 0; i < transformedPoints.length / 2; i++) {
    transformedPoints[i * 2] = width / 2 * (basePoints[i * 2] * cos - basePoints[i * 2 + 1] * sin);
    transformedPoints[i * 2 + 1] = height / 2 * (basePoints[i * 2 + 1] * cos + basePoints[i * 2] * sin);
    transformedPoints[i * 2] += centerX;
    transformedPoints[i * 2 + 1] += centerY;
  }
  var points;
  if (padding > 0) {
    var expandedLineSet = expandPolygon(transformedPoints, -padding);
    points = joinLines(expandedLineSet);
  } else {
    points = transformedPoints;
  }
  return pointInsidePolygonPoints(x, y, points);
};
var pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height, corners) {
  var cutPolygonPoints = new Array(basePoints.length * 2);
  for (var i = 0; i < corners.length; i++) {
    var corner = corners[i];
    cutPolygonPoints[i * 4 + 0] = corner.startX;
    cutPolygonPoints[i * 4 + 1] = corner.startY;
    cutPolygonPoints[i * 4 + 2] = corner.stopX;
    cutPolygonPoints[i * 4 + 3] = corner.stopY;
    var squaredDistance = Math.pow(corner.cx - x, 2) + Math.pow(corner.cy - y, 2);
    if (squaredDistance <= Math.pow(corner.radius, 2)) {
      return true;
    }
  }
  return pointInsidePolygonPoints(x, y, cutPolygonPoints);
};
var joinLines = function joinLines(lineSet) {
  var vertices = new Array(lineSet.length / 2);
  var currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY;
  var nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY;
  for (var i = 0; i < lineSet.length / 4; i++) {
    currentLineStartX = lineSet[i * 4];
    currentLineStartY = lineSet[i * 4 + 1];
    currentLineEndX = lineSet[i * 4 + 2];
    currentLineEndY = lineSet[i * 4 + 3];
    if (i < lineSet.length / 4 - 1) {
      nextLineStartX = lineSet[(i + 1) * 4];
      nextLineStartY = lineSet[(i + 1) * 4 + 1];
      nextLineEndX = lineSet[(i + 1) * 4 + 2];
      nextLineEndY = lineSet[(i + 1) * 4 + 3];
    } else {
      nextLineStartX = lineSet[0];
      nextLineStartY = lineSet[1];
      nextLineEndX = lineSet[2];
      nextLineEndY = lineSet[3];
    }
    var intersection = finiteLinesIntersect(currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY, nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY, true);
    vertices[i * 2] = intersection[0];
    vertices[i * 2 + 1] = intersection[1];
  }
  return vertices;
};
var expandPolygon = function expandPolygon(points, pad) {
  var expandedLineSet = new Array(points.length * 2);
  var currentPointX, currentPointY, nextPointX, nextPointY;
  for (var i = 0; i < points.length / 2; i++) {
    currentPointX = points[i * 2];
    currentPointY = points[i * 2 + 1];
    if (i < points.length / 2 - 1) {
      nextPointX = points[(i + 1) * 2];
      nextPointY = points[(i + 1) * 2 + 1];
    } else {
      nextPointX = points[0];
      nextPointY = points[1];
    }

    // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]

    // Assume CCW polygon winding

    var offsetX = nextPointY - currentPointY;
    var offsetY = -(nextPointX - currentPointX);

    // Normalize
    var offsetLength = Math.sqrt(offsetX * offsetX + offsetY * offsetY);
    var normalizedOffsetX = offsetX / offsetLength;
    var normalizedOffsetY = offsetY / offsetLength;
    expandedLineSet[i * 4] = currentPointX + normalizedOffsetX * pad;
    expandedLineSet[i * 4 + 1] = currentPointY + normalizedOffsetY * pad;
    expandedLineSet[i * 4 + 2] = nextPointX + normalizedOffsetX * pad;
    expandedLineSet[i * 4 + 3] = nextPointY + normalizedOffsetY * pad;
  }
  return expandedLineSet;
};
var intersectLineEllipse = function intersectLineEllipse(x, y, centerX, centerY, ellipseWradius, ellipseHradius) {
  var dispX = centerX - x;
  var dispY = centerY - y;
  dispX /= ellipseWradius;
  dispY /= ellipseHradius;
  var len = Math.sqrt(dispX * dispX + dispY * dispY);
  var newLength = len - 1;
  if (newLength < 0) {
    return [];
  }
  var lenProportion = newLength / len;
  return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];
};
var checkInEllipse = function checkInEllipse(x, y, width, height, centerX, centerY, padding) {
  x -= centerX;
  y -= centerY;
  x /= width / 2 + padding;
  y /= height / 2 + padding;
  return x * x + y * y <= 1;
};

// Returns intersections of increasing distance from line's start point
var intersectLineCircle = function intersectLineCircle(x1, y1, x2, y2, centerX, centerY, radius) {
  // Calculate d, direction vector of line
  var d = [x2 - x1, y2 - y1]; // Direction vector of line
  var f = [x1 - centerX, y1 - centerY];
  var a = d[0] * d[0] + d[1] * d[1];
  var b = 2 * (f[0] * d[0] + f[1] * d[1]);
  var c = f[0] * f[0] + f[1] * f[1] - radius * radius;
  var discriminant = b * b - 4 * a * c;
  if (discriminant < 0) {
    return [];
  }
  var t1 = (-b + Math.sqrt(discriminant)) / (2 * a);
  var t2 = (-b - Math.sqrt(discriminant)) / (2 * a);
  var tMin = Math.min(t1, t2);
  var tMax = Math.max(t1, t2);
  var inRangeParams = [];
  if (tMin >= 0 && tMin <= 1) {
    inRangeParams.push(tMin);
  }
  if (tMax >= 0 && tMax <= 1) {
    inRangeParams.push(tMax);
  }
  if (inRangeParams.length === 0) {
    return [];
  }
  var nearIntersectionX = inRangeParams[0] * d[0] + x1;
  var nearIntersectionY = inRangeParams[0] * d[1] + y1;
  if (inRangeParams.length > 1) {
    if (inRangeParams[0] == inRangeParams[1]) {
      return [nearIntersectionX, nearIntersectionY];
    } else {
      var farIntersectionX = inRangeParams[1] * d[0] + x1;
      var farIntersectionY = inRangeParams[1] * d[1] + y1;
      return [nearIntersectionX, nearIntersectionY, farIntersectionX, farIntersectionY];
    }
  } else {
    return [nearIntersectionX, nearIntersectionY];
  }
};
var midOfThree = function midOfThree(a, b, c) {
  if (b <= a && a <= c || c <= a && a <= b) {
    return a;
  } else if (a <= b && b <= c || c <= b && b <= a) {
    return b;
  } else {
    return c;
  }
};

// (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)
var finiteLinesIntersect = function finiteLinesIntersect(x1, y1, x2, y2, x3, y3, x4, y4, infiniteLines) {
  var dx13 = x1 - x3;
  var dx21 = x2 - x1;
  var dx43 = x4 - x3;
  var dy13 = y1 - y3;
  var dy21 = y2 - y1;
  var dy43 = y4 - y3;
  var ua_t = dx43 * dy13 - dy43 * dx13;
  var ub_t = dx21 * dy13 - dy21 * dx13;
  var u_b = dy43 * dx21 - dx43 * dy21;
  if (u_b !== 0) {
    var ua = ua_t / u_b;
    var ub = ub_t / u_b;
    var flptThreshold = 0.001;
    var _min = 0 - flptThreshold;
    var _max = 1 + flptThreshold;
    if (_min <= ua && ua <= _max && _min <= ub && ub <= _max) {
      return [x1 + ua * dx21, y1 + ua * dy21];
    } else {
      if (!infiniteLines) {
        return [];
      } else {
        return [x1 + ua * dx21, y1 + ua * dy21];
      }
    }
  } else {
    if (ua_t === 0 || ub_t === 0) {
      // Parallel, coincident lines. Check if overlap

      // Check endpoint of second line
      if (midOfThree(x1, x2, x4) === x4) {
        return [x4, y4];
      }

      // Check start point of second line
      if (midOfThree(x1, x2, x3) === x3) {
        return [x3, y3];
      }

      // Endpoint of first line
      if (midOfThree(x3, x4, x2) === x2) {
        return [x2, y2];
      }
      return [];
    } else {
      // Parallel, non-coincident
      return [];
    }
  }
};
var transformPoints = function transformPoints(points, centerX, centerY, width, height) {
  var ret = [];
  var halfW = width / 2;
  var halfH = height / 2;
  var x = centerX;
  var y = centerY;
  ret.push({
    x: x + halfW * points[0],
    y: y + halfH * points[1]
  });
  for (var i = 1; i < points.length / 2; i++) {
    ret.push({
      x: x + halfW * points[i * 2],
      y: y + halfH * points[i * 2 + 1]
    });
  }
  return ret;
};

// math.polygonIntersectLine( x, y, basePoints, centerX, centerY, width, height, padding )
// intersect a node polygon (pts transformed)
//
// math.polygonIntersectLine( x, y, basePoints, centerX, centerY )
// intersect the points (no transform)
var polygonIntersectLine = function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {
  var intersections = [];
  var intersection;
  var transformedPoints = new Array(basePoints.length);
  var doTransform = true;
  if (width == null) {
    doTransform = false;
  }
  var points;
  if (doTransform) {
    for (var i = 0; i < transformedPoints.length / 2; i++) {
      transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;
      transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;
    }
    if (padding > 0) {
      var expandedLineSet = expandPolygon(transformedPoints, -padding);
      points = joinLines(expandedLineSet);
    } else {
      points = transformedPoints;
    }
  } else {
    points = basePoints;
  }
  var currentX, currentY, nextX, nextY;
  for (var _i3 = 0; _i3 < points.length / 2; _i3++) {
    currentX = points[_i3 * 2];
    currentY = points[_i3 * 2 + 1];
    if (_i3 < points.length / 2 - 1) {
      nextX = points[(_i3 + 1) * 2];
      nextY = points[(_i3 + 1) * 2 + 1];
    } else {
      nextX = points[0];
      nextY = points[1];
    }
    intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);
    if (intersection.length !== 0) {
      intersections.push(intersection[0], intersection[1]);
    }
  }
  return intersections;
};
var roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding, corners) {
  var intersections = [];
  var intersection;
  var lines = new Array(basePoints.length * 2);
  corners.forEach(function (corner, i) {
    if (i === 0) {
      lines[lines.length - 2] = corner.startX;
      lines[lines.length - 1] = corner.startY;
    } else {
      lines[i * 4 - 2] = corner.startX;
      lines[i * 4 - 1] = corner.startY;
    }
    lines[i * 4] = corner.stopX;
    lines[i * 4 + 1] = corner.stopY;
    intersection = intersectLineCircle(x, y, centerX, centerY, corner.cx, corner.cy, corner.radius);
    if (intersection.length !== 0) {
      intersections.push(intersection[0], intersection[1]);
    }
  });
  for (var i = 0; i < lines.length / 4; i++) {
    intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[i * 4], lines[i * 4 + 1], lines[i * 4 + 2], lines[i * 4 + 3], false);
    if (intersection.length !== 0) {
      intersections.push(intersection[0], intersection[1]);
    }
  }
  if (intersections.length > 2) {
    var lowestIntersection = [intersections[0], intersections[1]];
    var lowestSquaredDistance = Math.pow(lowestIntersection[0] - x, 2) + Math.pow(lowestIntersection[1] - y, 2);
    for (var _i4 = 1; _i4 < intersections.length / 2; _i4++) {
      var squaredDistance = Math.pow(intersections[_i4 * 2] - x, 2) + Math.pow(intersections[_i4 * 2 + 1] - y, 2);
      if (squaredDistance <= lowestSquaredDistance) {
        lowestIntersection[0] = intersections[_i4 * 2];
        lowestIntersection[1] = intersections[_i4 * 2 + 1];
        lowestSquaredDistance = squaredDistance;
      }
    }
    return lowestIntersection;
  }
  return intersections;
};
var shortenIntersection = function shortenIntersection(intersection, offset, amount) {
  var disp = [intersection[0] - offset[0], intersection[1] - offset[1]];
  var length = Math.sqrt(disp[0] * disp[0] + disp[1] * disp[1]);
  var lenRatio = (length - amount) / length;
  if (lenRatio < 0) {
    lenRatio = 0.00001;
  }
  return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];
};
var generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {
  var points = generateUnitNgonPoints(sides, rotationRadians);
  points = fitPolygonToSquare(points);
  return points;
};
var fitPolygonToSquare = function fitPolygonToSquare(points) {
  var x, y;
  var sides = points.length / 2;
  var minX = Infinity,
    minY = Infinity,
    maxX = -Infinity,
    maxY = -Infinity;
  for (var i = 0; i < sides; i++) {
    x = points[2 * i];
    y = points[2 * i + 1];
    minX = Math.min(minX, x);
    maxX = Math.max(maxX, x);
    minY = Math.min(minY, y);
    maxY = Math.max(maxY, y);
  }

  // stretch factors
  var sx = 2 / (maxX - minX);
  var sy = 2 / (maxY - minY);
  for (var _i5 = 0; _i5 < sides; _i5++) {
    x = points[2 * _i5] = points[2 * _i5] * sx;
    y = points[2 * _i5 + 1] = points[2 * _i5 + 1] * sy;
    minX = Math.min(minX, x);
    maxX = Math.max(maxX, x);
    minY = Math.min(minY, y);
    maxY = Math.max(maxY, y);
  }
  if (minY < -1) {
    for (var _i6 = 0; _i6 < sides; _i6++) {
      y = points[2 * _i6 + 1] = points[2 * _i6 + 1] + (-1 - minY);
    }
  }
  return points;
};
var generateUnitNgonPoints = function generateUnitNgonPoints(sides, rotationRadians) {
  var increment = 1.0 / sides * 2 * Math.PI;
  var startAngle = sides % 2 === 0 ? Math.PI / 2.0 + increment / 2.0 : Math.PI / 2.0;
  startAngle += rotationRadians;
  var points = new Array(sides * 2);
  var currentAngle;
  for (var i = 0; i < sides; i++) {
    currentAngle = i * increment + startAngle;
    points[2 * i] = Math.cos(currentAngle); // x
    points[2 * i + 1] = Math.sin(-currentAngle); // y
  }
  return points;
};

// Set the default radius, unless half of width or height is smaller than default
var getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {
  return Math.min(width / 4, height / 4, 8);
};

// Set the default radius
var getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {
  return Math.min(width / 10, height / 10, 8);
};
var getCutRectangleCornerLength = function getCutRectangleCornerLength() {
  return 8;
};
var bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {
  return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];
};

// get curve width, height, and control point position offsets as a percentage of node height / width
var getBarrelCurveConstants = function getBarrelCurveConstants(width, height) {
  return {
    heightOffset: Math.min(15, 0.05 * height),
    widthOffset: Math.min(100, 0.25 * width),
    ctrlPtOffsetPct: 0.05
  };
};

// Separating Axis Theorem (SAT) to determine if two polygons intersect. 
// The function takes two polygons as input and returns a boolean value indicating 
// whether the two polygons intersect.
function satPolygonIntersection(poly1, poly2) {
  function getAxes(polygon) {
    var axes = [];
    for (var i = 0; i < polygon.length; i++) {
      var p1 = polygon[i];
      var p2 = polygon[(i + 1) % polygon.length];
      var edge = {
        x: p2.x - p1.x,
        y: p2.y - p1.y
      };
      var normal = {
        x: -edge.y,
        y: edge.x
      };
      var length = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
      axes.push({
        x: normal.x / length,
        y: normal.y / length
      });
    }
    return axes;
  }
  function project(polygon, axis) {
    var min = Infinity;
    var max = -Infinity;
    var _iterator = _createForOfIteratorHelper(polygon),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var point = _step.value;
        var projection = point.x * axis.x + point.y * axis.y;
        min = Math.min(min, projection);
        max = Math.max(max, projection);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return {
      min: min,
      max: max
    };
  }
  function overlaps(proj1, proj2) {
    return !(proj1.max < proj2.min || proj2.max < proj1.min);
  }
  var axes = [].concat(_toConsumableArray(getAxes(poly1)), _toConsumableArray(getAxes(poly2)));
  var _iterator2 = _createForOfIteratorHelper(axes),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var axis = _step2.value;
      var proj1 = project(poly1, axis);
      var proj2 = project(poly2, axis);
      if (!overlaps(proj1, proj2)) {
        return false; // No overlap, so the polygons do not intersect
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return true; // polygons intersect
}

var pageRankDefaults = defaults$g({
  dampingFactor: 0.8,
  precision: 0.000001,
  iterations: 200,
  weight: function weight(edge) {
    return 1;
  }
});
var elesfn$o = {
  pageRank: function pageRank(options) {
    var _pageRankDefaults = pageRankDefaults(options),
      dampingFactor = _pageRankDefaults.dampingFactor,
      precision = _pageRankDefaults.precision,
      iterations = _pageRankDefaults.iterations,
      weight = _pageRankDefaults.weight;
    var cy = this._private.cy;
    var _this$byGroup = this.byGroup(),
      nodes = _this$byGroup.nodes,
      edges = _this$byGroup.edges;
    var numNodes = nodes.length;
    var numNodesSqd = numNodes * numNodes;
    var numEdges = edges.length;

    // Construct transposed adjacency matrix
    // First lets have a zeroed matrix of the right size
    // We'll also keep track of the sum of each column
    var matrix = new Array(numNodesSqd);
    var columnSum = new Array(numNodes);
    var additionalProb = (1 - dampingFactor) / numNodes;

    // Create null matrix
    for (var i = 0; i < numNodes; i++) {
      for (var j = 0; j < numNodes; j++) {
        var n = i * numNodes + j;
        matrix[n] = 0;
      }
      columnSum[i] = 0;
    }

    // Now, process edges
    for (var _i = 0; _i < numEdges; _i++) {
      var edge = edges[_i];
      var srcId = edge.data('source');
      var tgtId = edge.data('target');

      // Don't include loops in the matrix
      if (srcId === tgtId) {
        continue;
      }
      var s = nodes.indexOfId(srcId);
      var t = nodes.indexOfId(tgtId);
      var w = weight(edge);
      var _n = t * numNodes + s;

      // Update matrix
      matrix[_n] += w;

      // Update column sum
      columnSum[s] += w;
    }

    // Add additional probability based on damping factor
    // Also, take into account columns that have sum = 0
    var p = 1.0 / numNodes + additionalProb; // Shorthand

    // Traverse matrix, column by column
    for (var _j = 0; _j < numNodes; _j++) {
      if (columnSum[_j] === 0) {
        // No 'links' out from node jth, assume equal probability for each possible node
        for (var _i2 = 0; _i2 < numNodes; _i2++) {
          var _n2 = _i2 * numNodes + _j;
          matrix[_n2] = p;
        }
      } else {
        // Node jth has outgoing link, compute normalized probabilities
        for (var _i3 = 0; _i3 < numNodes; _i3++) {
          var _n3 = _i3 * numNodes + _j;
          matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;
        }
      }
    }

    // Compute dominant eigenvector using power method
    var eigenvector = new Array(numNodes);
    var temp = new Array(numNodes);
    var previous;

    // Start with a vector of all 1's
    // Also, initialize a null vector which will be used as shorthand
    for (var _i4 = 0; _i4 < numNodes; _i4++) {
      eigenvector[_i4] = 1;
    }
    for (var iter = 0; iter < iterations; iter++) {
      // Temp array with all 0's
      for (var _i5 = 0; _i5 < numNodes; _i5++) {
        temp[_i5] = 0;
      }

      // Multiply matrix with previous result
      for (var _i6 = 0; _i6 < numNodes; _i6++) {
        for (var _j2 = 0; _j2 < numNodes; _j2++) {
          var _n4 = _i6 * numNodes + _j2;
          temp[_i6] += matrix[_n4] * eigenvector[_j2];
        }
      }
      inPlaceSumNormalize(temp);
      previous = eigenvector;
      eigenvector = temp;
      temp = previous;
      var diff = 0;
      // Compute difference (squared module) of both vectors
      for (var _i7 = 0; _i7 < numNodes; _i7++) {
        var delta = previous[_i7] - eigenvector[_i7];
        diff += delta * delta;
      }

      // If difference is less than the desired threshold, stop iterating
      if (diff < precision) {
        break;
      }
    }

    // Construct result
    var res = {
      rank: function rank(node) {
        node = cy.collection(node)[0];
        return eigenvector[nodes.indexOf(node)];
      }
    };
    return res;
  } // pageRank
}; // elesfn

var defaults$f = defaults$g({
  root: null,
  weight: function weight(edge) {
    return 1;
  },
  directed: false,
  alpha: 0
});
var elesfn$n = {
  degreeCentralityNormalized: function degreeCentralityNormalized(options) {
    options = defaults$f(options);
    var cy = this.cy();
    var nodes = this.nodes();
    var numNodes = nodes.length;
    if (!options.directed) {
      var degrees = {};
      var maxDegree = 0;
      for (var i = 0; i < numNodes; i++) {
        var node = nodes[i];

        // add current node to the current options object and call degreeCentrality
        options.root = node;
        var currDegree = this.degreeCentrality(options);
        if (maxDegree < currDegree.degree) {
          maxDegree = currDegree.degree;
        }
        degrees[node.id()] = currDegree.degree;
      }
      return {
        degree: function degree(node) {
          if (maxDegree === 0) {
            return 0;
          }
          if (string(node)) {
            // from is a selector string
            node = cy.filter(node);
          }
          return degrees[node.id()] / maxDegree;
        }
      };
    } else {
      var indegrees = {};
      var outdegrees = {};
      var maxIndegree = 0;
      var maxOutdegree = 0;
      for (var _i = 0; _i < numNodes; _i++) {
        var _node = nodes[_i];
        var id = _node.id();

        // add current node to the current options object and call degreeCentrality
        options.root = _node;
        var _currDegree = this.degreeCentrality(options);
        if (maxIndegree < _currDegree.indegree) maxIndegree = _currDegree.indegree;
        if (maxOutdegree < _currDegree.outdegree) maxOutdegree = _currDegree.outdegree;
        indegrees[id] = _currDegree.indegree;
        outdegrees[id] = _currDegree.outdegree;
      }
      return {
        indegree: function indegree(node) {
          if (maxIndegree == 0) {
            return 0;
          }
          if (string(node)) {
            // from is a selector string
            node = cy.filter(node);
          }
          return indegrees[node.id()] / maxIndegree;
        },
        outdegree: function outdegree(node) {
          if (maxOutdegree === 0) {
            return 0;
          }
          if (string(node)) {
            // from is a selector string
            node = cy.filter(node);
          }
          return outdegrees[node.id()] / maxOutdegree;
        }
      };
    }
  },
  // degreeCentralityNormalized

  // Implemented from the algorithm in Opsahl's paper
  // "Node centrality in weighted networks: Generalizing degree and shortest paths"
  // check the heading 2 "Degree"
  degreeCentrality: function degreeCentrality(options) {
    options = defaults$f(options);
    var cy = this.cy();
    var callingEles = this;
    var _options = options,
      root = _options.root,
      weight = _options.weight,
      directed = _options.directed,
      alpha = _options.alpha;
    root = cy.collection(root)[0];
    if (!directed) {
      var connEdges = root.connectedEdges().intersection(callingEles);
      var k = connEdges.length;
      var s = 0;

      // Now, sum edge weights
      for (var i = 0; i < connEdges.length; i++) {
        s += weight(connEdges[i]);
      }
      return {
        degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha)
      };
    } else {
      var edges = root.connectedEdges();
      var incoming = edges.filter(function (edge) {
        return edge.target().same(root) && callingEles.has(edge);
      });
      var outgoing = edges.filter(function (edge) {
        return edge.source().same(root) && callingEles.has(edge);
      });
      var k_in = incoming.length;
      var k_out = outgoing.length;
      var s_in = 0;
      var s_out = 0;

      // Now, sum incoming edge weights
      for (var _i2 = 0; _i2 < incoming.length; _i2++) {
        s_in += weight(incoming[_i2]);
      }

      // Now, sum outgoing edge weights
      for (var _i3 = 0; _i3 < outgoing.length; _i3++) {
        s_out += weight(outgoing[_i3]);
      }
      return {
        indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha),
        outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha)
      };
    }
  } // degreeCentrality
}; // elesfn

// nice, short mathematical alias
elesfn$n.dc = elesfn$n.degreeCentrality;
elesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;

var defaults$e = defaults$g({
  harmonic: true,
  weight: function weight() {
    return 1;
  },
  directed: false,
  root: null
});
var elesfn$m = {
  closenessCentralityNormalized: function closenessCentralityNormalized(options) {
    var _defaults = defaults$e(options),
      harmonic = _defaults.harmonic,
      weight = _defaults.weight,
      directed = _defaults.directed;
    var cy = this.cy();
    var closenesses = {};
    var maxCloseness = 0;
    var nodes = this.nodes();
    var fw = this.floydWarshall({
      weight: weight,
      directed: directed
    });

    // Compute closeness for every node and find the maximum closeness
    for (var i = 0; i < nodes.length; i++) {
      var currCloseness = 0;
      var node_i = nodes[i];
      for (var j = 0; j < nodes.length; j++) {
        if (i !== j) {
          var d = fw.distance(node_i, nodes[j]);
          if (harmonic) {
            currCloseness += 1 / d;
          } else {
            currCloseness += d;
          }
        }
      }
      if (!harmonic) {
        currCloseness = 1 / currCloseness;
      }
      if (maxCloseness < currCloseness) {
        maxCloseness = currCloseness;
      }
      closenesses[node_i.id()] = currCloseness;
    }
    return {
      closeness: function closeness(node) {
        if (maxCloseness == 0) {
          return 0;
        }
        if (string(node)) {
          // from is a selector string
          node = cy.filter(node)[0].id();
        } else {
          // from is a node
          node = node.id();
        }
        return closenesses[node] / maxCloseness;
      }
    };
  },
  // Implemented from pseudocode from wikipedia
  closenessCentrality: function closenessCentrality(options) {
    var _defaults2 = defaults$e(options),
      root = _defaults2.root,
      weight = _defaults2.weight,
      directed = _defaults2.directed,
      harmonic = _defaults2.harmonic;
    root = this.filter(root)[0];

    // we need distance from this node to every other node
    var dijkstra = this.dijkstra({
      root: root,
      weight: weight,
      directed: directed
    });
    var totalDistance = 0;
    var nodes = this.nodes();
    for (var i = 0; i < nodes.length; i++) {
      var n = nodes[i];
      if (!n.same(root)) {
        var d = dijkstra.distanceTo(n);
        if (harmonic) {
          totalDistance += 1 / d;
        } else {
          totalDistance += d;
        }
      }
    }
    return harmonic ? totalDistance : 1 / totalDistance;
  } // closenessCentrality
}; // elesfn

// nice, short mathematical alias
elesfn$m.cc = elesfn$m.closenessCentrality;
elesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;

var defaults$d = defaults$g({
  weight: null,
  directed: false
});
var elesfn$l = {
  // Implemented from the algorithm in the paper "On Variants of Shortest-Path Betweenness Centrality and their Generic Computation" by Ulrik Brandes
  betweennessCentrality: function betweennessCentrality(options) {
    var _defaults = defaults$d(options),
      directed = _defaults.directed,
      weight = _defaults.weight;
    var weighted = weight != null;
    var cy = this.cy();

    // starting
    var V = this.nodes();
    var A = {};
    var _C = {};
    var max = 0;
    var C = {
      set: function set(key, val) {
        _C[key] = val;
        if (val > max) {
          max = val;
        }
      },
      get: function get(key) {
        return _C[key];
      }
    };

    // A contains the neighborhoods of every node
    for (var i = 0; i < V.length; i++) {
      var v = V[i];
      var vid = v.id();
      if (directed) {
        A[vid] = v.outgoers().nodes(); // get outgoers of every node
      } else {
        A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node
      }
      C.set(vid, 0);
    }
    var _loop = function _loop() {
      var sid = V[s].id();
      var S = []; // stack
      var P = {};
      var g = {};
      var d = {};
      var Q = new Heap(function (a, b) {
        return d[a] - d[b];
      }); // queue

      // init dictionaries
      for (var _i = 0; _i < V.length; _i++) {
        var _vid = V[_i].id();
        P[_vid] = [];
        g[_vid] = 0;
        d[_vid] = Infinity;
      }
      g[sid] = 1; // sigma
      d[sid] = 0; // distance to s

      Q.push(sid);
      while (!Q.empty()) {
        var _v = Q.pop();
        S.push(_v);
        if (weighted) {
          for (var j = 0; j < A[_v].length; j++) {
            var w = A[_v][j];
            var vEle = cy.getElementById(_v);
            var edge = undefined;
            if (vEle.edgesTo(w).length > 0) {
              edge = vEle.edgesTo(w)[0];
            } else {
              edge = w.edgesTo(vEle)[0];
            }
            var edgeWeight = weight(edge);
            w = w.id();
            if (d[w] > d[_v] + edgeWeight) {
              d[w] = d[_v] + edgeWeight;
              if (Q.nodes.indexOf(w) < 0) {
                //if w is not in Q
                Q.push(w);
              } else {
                // update position if w is in Q
                Q.updateItem(w);
              }
              g[w] = 0;
              P[w] = [];
            }
            if (d[w] == d[_v] + edgeWeight) {
              g[w] = g[w] + g[_v];
              P[w].push(_v);
            }
          }
        } else {
          for (var _j = 0; _j < A[_v].length; _j++) {
            var _w = A[_v][_j].id();
            if (d[_w] == Infinity) {
              Q.push(_w);
              d[_w] = d[_v] + 1;
            }
            if (d[_w] == d[_v] + 1) {
              g[_w] = g[_w] + g[_v];
              P[_w].push(_v);
            }
          }
        }
      }
      var e = {};
      for (var _i2 = 0; _i2 < V.length; _i2++) {
        e[V[_i2].id()] = 0;
      }
      while (S.length > 0) {
        var _w2 = S.pop();
        for (var _j2 = 0; _j2 < P[_w2].length; _j2++) {
          var _v2 = P[_w2][_j2];
          e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]);
        }
        if (_w2 != V[s].id()) {
          C.set(_w2, C.get(_w2) + e[_w2]);
        }
      }
    };
    for (var s = 0; s < V.length; s++) {
      _loop();
    }
    var ret = {
      betweenness: function betweenness(node) {
        var id = cy.collection(node).id();
        return C.get(id);
      },
      betweennessNormalized: function betweennessNormalized(node) {
        if (max == 0) {
          return 0;
        }
        var id = cy.collection(node).id();
        return C.get(id) / max;
      }
    };

    // alias
    ret.betweennessNormalised = ret.betweennessNormalized;
    return ret;
  } // betweennessCentrality
}; // elesfn

// nice, short mathematical alias
elesfn$l.bc = elesfn$l.betweennessCentrality;

// Implemented by Zoe Xi @zoexi for GSOC 2016
// https://github.com/cytoscape/cytoscape.js-markov-cluster


/* eslint-disable no-unused-vars */
var defaults$c = defaults$g({
  expandFactor: 2,
  // affects time of computation and cluster granularity to some extent: M * M
  inflateFactor: 2,
  // affects cluster granularity (the greater the value, the more clusters): M(i,j) / E(j)
  multFactor: 1,
  // optional self loops for each node. Use a neutral value to improve cluster computations.
  maxIterations: 20,
  // maximum number of iterations of the MCL algorithm in a single run
  attributes: [
  // attributes/features used to group nodes, ie. similarity values between nodes
  function (edge) {
    return 1;
  }]
});
/* eslint-enable */

var setOptions$3 = function setOptions(options) {
  return defaults$c(options);
};
/* eslint-enable */

var getSimilarity$1 = function getSimilarity(edge, attributes) {
  var total = 0;
  for (var i = 0; i < attributes.length; i++) {
    total += attributes[i](edge);
  }
  return total;
};
var addLoops = function addLoops(M, n, val) {
  for (var i = 0; i < n; i++) {
    M[i * n + i] = val;
  }
};
var normalize = function normalize(M, n) {
  var sum;
  for (var col = 0; col < n; col++) {
    sum = 0;
    for (var row = 0; row < n; row++) {
      sum += M[row * n + col];
    }
    for (var _row = 0; _row < n; _row++) {
      M[_row * n + col] = M[_row * n + col] / sum;
    }
  }
};

// TODO: blocked matrix multiplication?
var mmult = function mmult(A, B, n) {
  var C = new Array(n * n);
  for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
      C[i * n + j] = 0;
    }
    for (var k = 0; k < n; k++) {
      for (var _j = 0; _j < n; _j++) {
        C[i * n + _j] += A[i * n + k] * B[k * n + _j];
      }
    }
  }
  return C;
};
var expand = function expand(M, n, expandFactor /** power **/) {
  var _M = M.slice(0);
  for (var p = 1; p < expandFactor; p++) {
    M = mmult(M, _M, n);
  }
  return M;
};
var inflate = function inflate(M, n, inflateFactor /** r **/) {
  var _M = new Array(n * n);

  // M(i,j) ^ inflatePower
  for (var i = 0; i < n * n; i++) {
    _M[i] = Math.pow(M[i], inflateFactor);
  }
  normalize(_M, n);
  return _M;
};
var hasConverged = function hasConverged(M, _M, n2, roundFactor) {
  // Check that both matrices have the same elements (i,j)
  for (var i = 0; i < n2; i++) {
    var v1 = Math.round(M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor); // truncate to 'roundFactor' decimal places
    var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);
    if (v1 !== v2) {
      return false;
    }
  }
  return true;
};
var assign$2 = function assign(M, n, nodes, cy) {
  var clusters = [];
  for (var i = 0; i < n; i++) {
    var cluster = [];
    for (var j = 0; j < n; j++) {
      // Row-wise attractors and elements that they attract belong in same cluster
      if (Math.round(M[i * n + j] * 1000) / 1000 > 0) {
        cluster.push(nodes[j]);
      }
    }
    if (cluster.length !== 0) {
      clusters.push(cy.collection(cluster));
    }
  }
  return clusters;
};
var isDuplicate = function isDuplicate(c1, c2) {
  for (var i = 0; i < c1.length; i++) {
    if (!c2[i] || c1[i].id() !== c2[i].id()) {
      return false;
    }
  }
  return true;
};
var removeDuplicates = function removeDuplicates(clusters) {
  for (var i = 0; i < clusters.length; i++) {
    for (var j = 0; j < clusters.length; j++) {
      if (i != j && isDuplicate(clusters[i], clusters[j])) {
        clusters.splice(j, 1);
      }
    }
  }
  return clusters;
};
var markovClustering = function markovClustering(options) {
  var nodes = this.nodes();
  var edges = this.edges();
  var cy = this.cy();

  // Set parameters of algorithm:
  var opts = setOptions$3(options);

  // Map each node to its position in node array
  var id2position = {};
  for (var i = 0; i < nodes.length; i++) {
    id2position[nodes[i].id()] = i;
  }

  // Generate stochastic matrix M from input graph G (should be symmetric/undirected)
  var n = nodes.length,
    n2 = n * n;
  var M = new Array(n2),
    _M;
  for (var _i = 0; _i < n2; _i++) {
    M[_i] = 0;
  }
  for (var e = 0; e < edges.length; e++) {
    var edge = edges[e];
    var _i2 = id2position[edge.source().id()];
    var j = id2position[edge.target().id()];
    var sim = getSimilarity$1(edge, opts.attributes);
    M[_i2 * n + j] += sim; // G should be symmetric and undirected
    M[j * n + _i2] += sim;
  }

  // Begin Markov cluster algorithm

  // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal
  addLoops(M, n, opts.multFactor);

  // Step 2: M = normalize( M );
  normalize(M, n);
  var isStillMoving = true;
  var iterations = 0;
  while (isStillMoving && iterations < opts.maxIterations) {
    isStillMoving = false;

    // Step 3:
    _M = expand(M, n, opts.expandFactor);

    // Step 4:
    M = inflate(_M, n, opts.inflateFactor);

    // Step 5: check to see if ~steady state has been reached
    if (!hasConverged(M, _M, n2, 4)) {
      isStillMoving = true;
    }
    iterations++;
  }

  // Build clusters from matrix
  var clusters = assign$2(M, n, nodes, cy);

  // Remove duplicate clusters due to symmetry of graph and M matrix
  clusters = removeDuplicates(clusters);
  return clusters;
};
var markovClustering$1 = {
  markovClustering: markovClustering,
  mcl: markovClustering
};

// Common distance metrics for clustering algorithms
// https://en.wikipedia.org/wiki/Hierarchical_clustering#Metric

var identity$1 = function identity(x) {
  return x;
};
var absDiff = function absDiff(p, q) {
  return Math.abs(q - p);
};
var addAbsDiff = function addAbsDiff(total, p, q) {
  return total + absDiff(p, q);
};
var addSquaredDiff = function addSquaredDiff(total, p, q) {
  return total + Math.pow(q - p, 2);
};
var sqrt = function sqrt(x) {
  return Math.sqrt(x);
};
var maxAbsDiff = function maxAbsDiff(currentMax, p, q) {
  return Math.max(currentMax, absDiff(p, q));
};
var getDistance = function getDistance(length, getP, getQ, init, visit) {
  var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity$1;
  var ret = init;
  var p, q;
  for (var dim = 0; dim < length; dim++) {
    p = getP(dim);
    q = getQ(dim);
    ret = visit(ret, p, q);
  }
  return post(ret);
};
var distances = {
  euclidean: function euclidean(length, getP, getQ) {
    if (length >= 2) {
      return getDistance(length, getP, getQ, 0, addSquaredDiff, sqrt);
    } else {
      // for single attr case, more efficient to avoid sqrt
      return getDistance(length, getP, getQ, 0, addAbsDiff);
    }
  },
  squaredEuclidean: function squaredEuclidean(length, getP, getQ) {
    return getDistance(length, getP, getQ, 0, addSquaredDiff);
  },
  manhattan: function manhattan(length, getP, getQ) {
    return getDistance(length, getP, getQ, 0, addAbsDiff);
  },
  max: function max(length, getP, getQ) {
    return getDistance(length, getP, getQ, -Infinity, maxAbsDiff);
  }
};

// in case the user accidentally doesn't use camel case
distances['squared-euclidean'] = distances['squaredEuclidean'];
distances['squaredeuclidean'] = distances['squaredEuclidean'];
function clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {
  var impl;
  if (fn$6(method)) {
    impl = method;
  } else {
    impl = distances[method] || distances.euclidean;
  }
  if (length === 0 && fn$6(method)) {
    return impl(nodeP, nodeQ);
  } else {
    return impl(length, getP, getQ, nodeP, nodeQ);
  }
}

var defaults$b = defaults$g({
  k: 2,
  m: 2,
  sensitivityThreshold: 0.0001,
  distance: 'euclidean',
  maxIterations: 10,
  attributes: [],
  testMode: false,
  testCentroids: null
});
var setOptions$2 = function setOptions(options) {
  return defaults$b(options);
};

var getDist = function getDist(type, node, centroid, attributes, mode) {
  var noNodeP = mode !== 'kMedoids';
  var getP = noNodeP ? function (i) {
    return centroid[i];
  } : function (i) {
    return attributes[i](centroid);
  };
  var getQ = function getQ(i) {
    return attributes[i](node);
  };
  var nodeP = centroid;
  var nodeQ = node;
  return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);
};
var randomCentroids = function randomCentroids(nodes, k, attributes) {
  var ndim = attributes.length;
  var min = new Array(ndim);
  var max = new Array(ndim);
  var centroids = new Array(k);
  var centroid = null;

  // Find min, max values for each attribute dimension
  for (var i = 0; i < ndim; i++) {
    min[i] = nodes.min(attributes[i]).value;
    max[i] = nodes.max(attributes[i]).value;
  }

  // Build k centroids, each represented as an n-dim feature vector
  for (var c = 0; c < k; c++) {
    centroid = [];
    for (var _i = 0; _i < ndim; _i++) {
      centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value
    }
    centroids[c] = centroid;
  }
  return centroids;
};
var classify = function classify(node, centroids, distance, attributes, type) {
  var min = Infinity;
  var index = 0;
  for (var i = 0; i < centroids.length; i++) {
    var dist = getDist(distance, node, centroids[i], attributes, type);
    if (dist < min) {
      min = dist;
      index = i;
    }
  }
  return index;
};
var buildCluster = function buildCluster(centroid, nodes, assignment) {
  var cluster = [];
  var node = null;
  for (var n = 0; n < nodes.length; n++) {
    node = nodes[n];
    if (assignment[node.id()] === centroid) {
      //console.log("Node " + node.id() + " is associated with medoid #: " + m);
      cluster.push(node);
    }
  }
  return cluster;
};
var haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {
  return Math.abs(v2 - v1) <= sensitivityThreshold;
};
var haveMatricesConverged = function haveMatricesConverged(v1, v2, sensitivityThreshold) {
  for (var i = 0; i < v1.length; i++) {
    for (var j = 0; j < v1[i].length; j++) {
      var diff = Math.abs(v1[i][j] - v2[i][j]);
      if (diff > sensitivityThreshold) {
        return false;
      }
    }
  }
  return true;
};
var seenBefore = function seenBefore(node, medoids, n) {
  for (var i = 0; i < n; i++) {
    if (node === medoids[i]) return true;
  }
  return false;
};
var randomMedoids = function randomMedoids(nodes, k) {
  var medoids = new Array(k);

  // For small data sets, the probability of medoid conflict is greater,
  // so we need to check to see if we've already seen or chose this node before.
  if (nodes.length < 50) {
    // Randomly select k medoids from the n nodes
    for (var i = 0; i < k; i++) {
      var node = nodes[Math.floor(Math.random() * nodes.length)];

      // If we've already chosen this node to be a medoid, don't choose it again (for small data sets).
      // Instead choose a different random node.
      while (seenBefore(node, medoids, i)) {
        node = nodes[Math.floor(Math.random() * nodes.length)];
      }
      medoids[i] = node;
    }
  } else {
    // Relatively large data set, so pretty safe to not check and just select random nodes
    for (var _i2 = 0; _i2 < k; _i2++) {
      medoids[_i2] = nodes[Math.floor(Math.random() * nodes.length)];
    }
  }
  return medoids;
};
var findCost = function findCost(potentialNewMedoid, cluster, attributes) {
  var cost = 0;
  for (var n = 0; n < cluster.length; n++) {
    cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');
  }
  return cost;
};
var kMeans = function kMeans(options) {
  var cy = this.cy();
  var nodes = this.nodes();
  var node = null;

  // Set parameters of algorithm: # of clusters, distance metric, etc.
  var opts = setOptions$2(options);

  // Begin k-means algorithm
  var clusters = new Array(opts.k);
  var assignment = {};
  var centroids;

  // Step 1: Initialize centroid positions
  if (opts.testMode) {
    if (typeof opts.testCentroids === 'number') {
      // TODO: implement a seeded random number generator.
      opts.testCentroids;
      centroids = randomCentroids(nodes, opts.k, opts.attributes);
    } else if (_typeof(opts.testCentroids) === 'object') {
      centroids = opts.testCentroids;
    } else {
      centroids = randomCentroids(nodes, opts.k, opts.attributes);
    }
  } else {
    centroids = randomCentroids(nodes, opts.k, opts.attributes);
  }
  var isStillMoving = true;
  var iterations = 0;
  while (isStillMoving && iterations < opts.maxIterations) {
    // Step 2: Assign nodes to the nearest centroid
    for (var n = 0; n < nodes.length; n++) {
      node = nodes[n];
      // Determine which cluster this node belongs to: node id => cluster #
      assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');
    }

    // Step 3: For each of the k clusters, update its centroid
    isStillMoving = false;
    for (var c = 0; c < opts.k; c++) {
      // Get all nodes that belong to this cluster
      var cluster = buildCluster(c, nodes, assignment);
      if (cluster.length === 0) {
        // If cluster is empty, break out early & move to next cluster
        continue;
      }

      // Update centroids by calculating avg of all nodes within the cluster.
      var ndim = opts.attributes.length;
      var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]
      var newCentroid = new Array(ndim);
      var sum = new Array(ndim);
      for (var d = 0; d < ndim; d++) {
        sum[d] = 0.0;
        for (var i = 0; i < cluster.length; i++) {
          node = cluster[i];
          sum[d] += opts.attributes[d](node);
        }
        newCentroid[d] = sum[d] / cluster.length;

        // Check to see if algorithm has converged, i.e. when centroids no longer change
        if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {
          isStillMoving = true;
        }
      }
      centroids[c] = newCentroid;
      clusters[c] = cy.collection(cluster);
    }
    iterations++;
  }
  return clusters;
};
var kMedoids = function kMedoids(options) {
  var cy = this.cy();
  var nodes = this.nodes();
  var node = null;
  var opts = setOptions$2(options);

  // Begin k-medoids algorithm
  var clusters = new Array(opts.k);
  var medoids;
  var assignment = {};
  var curCost;
  var minCosts = new Array(opts.k); // minimum cost configuration for each cluster

  // Step 1: Initialize k medoids
  if (opts.testMode) {
    if (typeof opts.testCentroids === 'number') ; else if (_typeof(opts.testCentroids) === 'object') {
      medoids = opts.testCentroids;
    } else {
      medoids = randomMedoids(nodes, opts.k);
    }
  } else {
    medoids = randomMedoids(nodes, opts.k);
  }
  var isStillMoving = true;
  var iterations = 0;
  while (isStillMoving && iterations < opts.maxIterations) {
    // Step 2: Assign nodes to the nearest medoid
    for (var n = 0; n < nodes.length; n++) {
      node = nodes[n];
      // Determine which cluster this node belongs to: node id => cluster #
      assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');
    }
    isStillMoving = false;
    // Step 3: For each medoid m, and for each node associated with mediod m,
    // select the node with the lowest configuration cost as new medoid.
    for (var m = 0; m < medoids.length; m++) {
      // Get all nodes that belong to this medoid
      var cluster = buildCluster(m, nodes, assignment);
      if (cluster.length === 0) {
        // If cluster is empty, break out early & move to next cluster
        continue;
      }
      minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost

      // Select different medoid if its configuration has the lowest cost
      for (var _n = 0; _n < cluster.length; _n++) {
        curCost = findCost(cluster[_n], cluster, opts.attributes);
        if (curCost < minCosts[m]) {
          minCosts[m] = curCost;
          medoids[m] = cluster[_n];
          isStillMoving = true;
        }
      }
      clusters[m] = cy.collection(cluster);
    }
    iterations++;
  }
  return clusters;
};
var updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {
  var numerator, denominator;
  for (var n = 0; n < nodes.length; n++) {
    for (var c = 0; c < centroids.length; c++) {
      weight[n][c] = Math.pow(U[n][c], opts.m);
    }
  }
  for (var _c = 0; _c < centroids.length; _c++) {
    for (var dim = 0; dim < opts.attributes.length; dim++) {
      numerator = 0;
      denominator = 0;
      for (var _n2 = 0; _n2 < nodes.length; _n2++) {
        numerator += weight[_n2][_c] * opts.attributes[dim](nodes[_n2]);
        denominator += weight[_n2][_c];
      }
      centroids[_c][dim] = numerator / denominator;
    }
  }
};
var updateMembership = function updateMembership(U, _U, centroids, nodes, opts) {
  // Save previous step
  for (var i = 0; i < U.length; i++) {
    _U[i] = U[i].slice();
  }
  var sum, numerator, denominator;
  var pow = 2 / (opts.m - 1);
  for (var c = 0; c < centroids.length; c++) {
    for (var n = 0; n < nodes.length; n++) {
      sum = 0;
      for (var k = 0; k < centroids.length; k++) {
        // against all other centroids
        numerator = getDist(opts.distance, nodes[n], centroids[c], opts.attributes, 'cmeans');
        denominator = getDist(opts.distance, nodes[n], centroids[k], opts.attributes, 'cmeans');
        sum += Math.pow(numerator / denominator, pow);
      }
      U[n][c] = 1 / sum;
    }
  }
};
var assign$1 = function assign(nodes, U, opts, cy) {
  var clusters = new Array(opts.k);
  for (var c = 0; c < clusters.length; c++) {
    clusters[c] = [];
  }
  var max;
  var index;
  for (var n = 0; n < U.length; n++) {
    // for each node (U is N x C matrix)
    max = -Infinity;
    index = -1;
    // Determine which cluster the node is most likely to belong in
    for (var _c2 = 0; _c2 < U[0].length; _c2++) {
      if (U[n][_c2] > max) {
        max = U[n][_c2];
        index = _c2;
      }
    }
    clusters[index].push(nodes[n]);
  }

  // Turn every array into a collection of nodes
  for (var _c3 = 0; _c3 < clusters.length; _c3++) {
    clusters[_c3] = cy.collection(clusters[_c3]);
  }
  return clusters;
};
var fuzzyCMeans = function fuzzyCMeans(options) {
  var cy = this.cy();
  var nodes = this.nodes();
  var opts = setOptions$2(options);

  // Begin fuzzy c-means algorithm
  var clusters;
  var centroids;
  var U;
  var _U;
  var weight;

  // Step 1: Initialize letiables.
  _U = new Array(nodes.length);
  for (var i = 0; i < nodes.length; i++) {
    // N x C matrix
    _U[i] = new Array(opts.k);
  }
  U = new Array(nodes.length);
  for (var _i3 = 0; _i3 < nodes.length; _i3++) {
    // N x C matrix
    U[_i3] = new Array(opts.k);
  }
  for (var _i4 = 0; _i4 < nodes.length; _i4++) {
    var total = 0;
    for (var j = 0; j < opts.k; j++) {
      U[_i4][j] = Math.random();
      total += U[_i4][j];
    }
    for (var _j = 0; _j < opts.k; _j++) {
      U[_i4][_j] = U[_i4][_j] / total;
    }
  }
  centroids = new Array(opts.k);
  for (var _i5 = 0; _i5 < opts.k; _i5++) {
    centroids[_i5] = new Array(opts.attributes.length);
  }
  weight = new Array(nodes.length);
  for (var _i6 = 0; _i6 < nodes.length; _i6++) {
    // N x C matrix
    weight[_i6] = new Array(opts.k);
  }
  // end init FCM

  var isStillMoving = true;
  var iterations = 0;
  while (isStillMoving && iterations < opts.maxIterations) {
    isStillMoving = false;

    // Step 2: Calculate the centroids for each step.
    updateCentroids(centroids, nodes, U, weight, opts);

    // Step 3: Update the partition matrix U.
    updateMembership(U, _U, centroids, nodes, opts);

    // Step 4: Check for convergence.
    if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {
      isStillMoving = true;
    }
    iterations++;
  }

  // Assign nodes to clusters with highest probability.
  clusters = assign$1(nodes, U, opts, cy);
  return {
    clusters: clusters,
    degreeOfMembership: U
  };
};
var kClustering = {
  kMeans: kMeans,
  kMedoids: kMedoids,
  fuzzyCMeans: fuzzyCMeans,
  fcm: fuzzyCMeans
};

// Implemented by Zoe Xi @zoexi for GSOC 2016
// https://github.com/cytoscape/cytoscape.js-hierarchical

var defaults$a = defaults$g({
  distance: 'euclidean',
  // distance metric to compare nodes
  linkage: 'min',
  // linkage criterion : how to determine the distance between clusters of nodes
  mode: 'threshold',
  // mode:'threshold' => clusters must be threshold distance apart
  threshold: Infinity,
  // the distance threshold
  // mode:'dendrogram' => the nodes are organised as leaves in a tree (siblings are close), merging makes clusters
  addDendrogram: false,
  // whether to add the dendrogram to the graph for viz
  dendrogramDepth: 0,
  // depth at which dendrogram branches are merged into the returned clusters
  attributes: [] // array of attr functions
});
var linkageAliases = {
  'single': 'min',
  'complete': 'max'
};
var setOptions$1 = function setOptions(options) {
  var opts = defaults$a(options);
  var preferredAlias = linkageAliases[opts.linkage];
  if (preferredAlias != null) {
    opts.linkage = preferredAlias;
  }
  return opts;
};
var mergeClosest = function mergeClosest(clusters, index, dists, mins, opts) {
  // Find two closest clusters from cached mins
  var minKey = 0;
  var min = Infinity;
  var dist;
  var attrs = opts.attributes;
  var getDist = function getDist(n1, n2) {
    return clusteringDistance(opts.distance, attrs.length, function (i) {
      return attrs[i](n1);
    }, function (i) {
      return attrs[i](n2);
    }, n1, n2);
  };
  for (var i = 0; i < clusters.length; i++) {
    var key = clusters[i].key;
    var _dist = dists[key][mins[key]];
    if (_dist < min) {
      minKey = key;
      min = _dist;
    }
  }
  if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {
    return false;
  }
  var c1 = index[minKey];
  var c2 = index[mins[minKey]];
  var merged;

  // Merge two closest clusters
  if (opts.mode === 'dendrogram') {
    merged = {
      left: c1,
      right: c2,
      key: c1.key
    };
  } else {
    merged = {
      value: c1.value.concat(c2.value),
      key: c1.key
    };
  }
  clusters[c1.index] = merged;
  clusters.splice(c2.index, 1);
  index[c1.key] = merged;

  // Update distances with new merged cluster
  for (var _i = 0; _i < clusters.length; _i++) {
    var cur = clusters[_i];
    if (c1.key === cur.key) {
      dist = Infinity;
    } else if (opts.linkage === 'min') {
      dist = dists[c1.key][cur.key];
      if (dists[c1.key][cur.key] > dists[c2.key][cur.key]) {
        dist = dists[c2.key][cur.key];
      }
    } else if (opts.linkage === 'max') {
      dist = dists[c1.key][cur.key];
      if (dists[c1.key][cur.key] < dists[c2.key][cur.key]) {
        dist = dists[c2.key][cur.key];
      }
    } else if (opts.linkage === 'mean') {
      dist = (dists[c1.key][cur.key] * c1.size + dists[c2.key][cur.key] * c2.size) / (c1.size + c2.size);
    } else {
      if (opts.mode === 'dendrogram') dist = getDist(cur.value, c1.value);else dist = getDist(cur.value[0], c1.value[0]);
    }
    dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric
  }

  // Update cached mins
  for (var _i2 = 0; _i2 < clusters.length; _i2++) {
    var key1 = clusters[_i2].key;
    if (mins[key1] === c1.key || mins[key1] === c2.key) {
      var _min = key1;
      for (var j = 0; j < clusters.length; j++) {
        var key2 = clusters[j].key;
        if (dists[key1][key2] < dists[key1][_min]) {
          _min = key2;
        }
      }
      mins[key1] = _min;
    }
    clusters[_i2].index = _i2;
  }

  // Clean up meta data used for clustering
  c1.key = c2.key = c1.index = c2.index = null;
  return true;
};
var _getAllChildren = function getAllChildren(root, arr, cy) {
  if (!root) return;
  if (root.value) {
    arr.push(root.value);
  } else {
    if (root.left) _getAllChildren(root.left, arr);
    if (root.right) _getAllChildren(root.right, arr);
  }
};
var _buildDendrogram = function buildDendrogram(root, cy) {
  if (!root) return '';
  if (root.left && root.right) {
    var leftStr = _buildDendrogram(root.left, cy);
    var rightStr = _buildDendrogram(root.right, cy);
    var node = cy.add({
      group: 'nodes',
      data: {
        id: leftStr + ',' + rightStr
      }
    });
    cy.add({
      group: 'edges',
      data: {
        source: leftStr,
        target: node.id()
      }
    });
    cy.add({
      group: 'edges',
      data: {
        source: rightStr,
        target: node.id()
      }
    });
    return node.id();
  } else if (root.value) {
    return root.value.id();
  }
};
var _buildClustersFromTree = function buildClustersFromTree(root, k, cy) {
  if (!root) return [];
  var left = [],
    right = [],
    leaves = [];
  if (k === 0) {
    // don't cut tree, simply return all nodes as 1 single cluster
    if (root.left) _getAllChildren(root.left, left);
    if (root.right) _getAllChildren(root.right, right);
    leaves = left.concat(right);
    return [cy.collection(leaves)];
  } else if (k === 1) {
    // cut at root

    if (root.value) {
      // leaf node
      return [cy.collection(root.value)];
    } else {
      if (root.left) _getAllChildren(root.left, left);
      if (root.right) _getAllChildren(root.right, right);
      return [cy.collection(left), cy.collection(right)];
    }
  } else {
    if (root.value) {
      return [cy.collection(root.value)];
    } else {
      if (root.left) left = _buildClustersFromTree(root.left, k - 1, cy);
      if (root.right) right = _buildClustersFromTree(root.right, k - 1, cy);
      return left.concat(right);
    }
  }
};

var hierarchicalClustering = function hierarchicalClustering(options) {
  var cy = this.cy();
  var nodes = this.nodes();

  // Set parameters of algorithm: linkage type, distance metric, etc.
  var opts = setOptions$1(options);
  var attrs = opts.attributes;
  var getDist = function getDist(n1, n2) {
    return clusteringDistance(opts.distance, attrs.length, function (i) {
      return attrs[i](n1);
    }, function (i) {
      return attrs[i](n2);
    }, n1, n2);
  };

  // Begin hierarchical algorithm
  var clusters = [];
  var dists = []; // distances between each pair of clusters
  var mins = []; // closest cluster for each cluster
  var index = []; // hash of all clusters by key

  // In agglomerative (bottom-up) clustering, each node starts as its own cluster
  for (var n = 0; n < nodes.length; n++) {
    var cluster = {
      value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],
      key: n,
      index: n
    };
    clusters[n] = cluster;
    index[n] = cluster;
    dists[n] = [];
    mins[n] = 0;
  }

  // Calculate the distance between each pair of clusters
  for (var i = 0; i < clusters.length; i++) {
    for (var j = 0; j <= i; j++) {
      var dist = undefined;
      if (opts.mode === 'dendrogram') {
        // modes store cluster values differently
        dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);
      } else {
        dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);
      }
      dists[i][j] = dist;
      dists[j][i] = dist;
      if (dist < dists[i][mins[i]]) {
        mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j
      }
    }
  }

  // Find the closest pair of clusters and merge them into a single cluster.
  // Update distances between new cluster and each of the old clusters, and loop until threshold reached.
  var merged = mergeClosest(clusters, index, dists, mins, opts);
  while (merged) {
    merged = mergeClosest(clusters, index, dists, mins, opts);
  }
  var retClusters;

  // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges
  // in addition to returning the clusters.
  if (opts.mode === 'dendrogram') {
    retClusters = _buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);
    if (opts.addDendrogram) _buildDendrogram(clusters[0], cy);
  } else {
    // Regular mode simply returns the clusters

    retClusters = new Array(clusters.length);
    clusters.forEach(function (cluster, i) {
      // Clean up meta data used for clustering
      cluster.key = cluster.index = null;
      retClusters[i] = cy.collection(cluster.value);
    });
  }
  return retClusters;
};
var hierarchicalClustering$1 = {
  hierarchicalClustering: hierarchicalClustering,
  hca: hierarchicalClustering
};

// Implemented by Zoe Xi @zoexi for GSOC 2016
// https://github.com/cytoscape/cytoscape.js-affinity-propagation

var defaults$9 = defaults$g({
  distance: 'euclidean',
  // distance metric to compare attributes between two nodes
  preference: 'median',
  // suitability of a data point to serve as an exemplar
  damping: 0.8,
  // damping factor between [0.5, 1)
  maxIterations: 1000,
  // max number of iterations to run
  minIterations: 100,
  // min number of iterations to run in order for clustering to stop
  attributes: [// functions to quantify the similarity between any two points
    // e.g. node => node.data('weight')
  ]
});
var setOptions = function setOptions(options) {
  var dmp = options.damping;
  var pref = options.preference;
  if (!(0.5 <= dmp && dmp < 1)) {
    error("Damping must range on [0.5, 1).  Got: ".concat(dmp));
  }
  var validPrefs = ['median', 'mean', 'min', 'max'];
  if (!(validPrefs.some(function (v) {
    return v === pref;
  }) || number$1(pref))) {
    error("Preference must be one of [".concat(validPrefs.map(function (p) {
      return "'".concat(p, "'");
    }).join(', '), "] or a number.  Got: ").concat(pref));
  }
  return defaults$9(options);
};

var getSimilarity = function getSimilarity(type, n1, n2, attributes) {
  var attr = function attr(n, i) {
    return attributes[i](n);
  };

  // nb negative because similarity should have an inverse relationship to distance
  return -clusteringDistance(type, attributes.length, function (i) {
    return attr(n1, i);
  }, function (i) {
    return attr(n2, i);
  }, n1, n2);
};
var getPreference = function getPreference(S, preference) {
  // larger preference = greater # of clusters
  var p = null;
  if (preference === 'median') {
    p = median(S);
  } else if (preference === 'mean') {
    p = mean(S);
  } else if (preference === 'min') {
    p = min(S);
  } else if (preference === 'max') {
    p = max(S);
  } else {
    // Custom preference number, as set by user
    p = preference;
  }
  return p;
};
var findExemplars = function findExemplars(n, R, A) {
  var indices = [];
  for (var i = 0; i < n; i++) {
    if (R[i * n + i] + A[i * n + i] > 0) {
      indices.push(i);
    }
  }
  return indices;
};
var assignClusters = function assignClusters(n, S, exemplars) {
  var clusters = [];
  for (var i = 0; i < n; i++) {
    var index = -1;
    var max = -Infinity;
    for (var ei = 0; ei < exemplars.length; ei++) {
      var e = exemplars[ei];
      if (S[i * n + e] > max) {
        index = e;
        max = S[i * n + e];
      }
    }
    if (index > 0) {
      clusters.push(index);
    }
  }
  for (var _ei = 0; _ei < exemplars.length; _ei++) {
    clusters[exemplars[_ei]] = exemplars[_ei];
  }
  return clusters;
};
var assign = function assign(n, S, exemplars) {
  var clusters = assignClusters(n, S, exemplars);
  for (var ei = 0; ei < exemplars.length; ei++) {
    var ii = [];
    for (var c = 0; c < clusters.length; c++) {
      if (clusters[c] === exemplars[ei]) {
        ii.push(c);
      }
    }
    var maxI = -1;
    var maxSum = -Infinity;
    for (var i = 0; i < ii.length; i++) {
      var sum = 0;
      for (var j = 0; j < ii.length; j++) {
        sum += S[ii[j] * n + ii[i]];
      }
      if (sum > maxSum) {
        maxI = i;
        maxSum = sum;
      }
    }
    exemplars[ei] = ii[maxI];
  }
  clusters = assignClusters(n, S, exemplars);
  return clusters;
};
var affinityPropagation = function affinityPropagation(options) {
  var cy = this.cy();
  var nodes = this.nodes();
  var opts = setOptions(options);

  // Map each node to its position in node array
  var id2position = {};
  for (var i = 0; i < nodes.length; i++) {
    id2position[nodes[i].id()] = i;
  }

  // Begin affinity propagation algorithm

  var n; // number of data points
  var n2; // size of matrices
  var S; // similarity matrix (1D array)
  var p; // preference/suitability of a data point to serve as an exemplar
  var R; // responsibility matrix (1D array)
  var A; // availability matrix (1D array)

  n = nodes.length;
  n2 = n * n;

  // Initialize and build S similarity matrix
  S = new Array(n2);
  for (var _i = 0; _i < n2; _i++) {
    S[_i] = -Infinity; // for cases where two data points shouldn't be linked together
  }
  for (var _i2 = 0; _i2 < n; _i2++) {
    for (var j = 0; j < n; j++) {
      if (_i2 !== j) {
        S[_i2 * n + j] = getSimilarity(opts.distance, nodes[_i2], nodes[j], opts.attributes);
      }
    }
  }

  // Place preferences on the diagonal of S
  p = getPreference(S, opts.preference);
  for (var _i3 = 0; _i3 < n; _i3++) {
    S[_i3 * n + _i3] = p;
  }

  // Initialize R responsibility matrix
  R = new Array(n2);
  for (var _i4 = 0; _i4 < n2; _i4++) {
    R[_i4] = 0.0;
  }

  // Initialize A availability matrix
  A = new Array(n2);
  for (var _i5 = 0; _i5 < n2; _i5++) {
    A[_i5] = 0.0;
  }
  var old = new Array(n);
  var Rp = new Array(n);
  var se = new Array(n);
  for (var _i6 = 0; _i6 < n; _i6++) {
    old[_i6] = 0.0;
    Rp[_i6] = 0.0;
    se[_i6] = 0;
  }
  var e = new Array(n * opts.minIterations);
  for (var _i7 = 0; _i7 < e.length; _i7++) {
    e[_i7] = 0;
  }
  var iter;
  for (iter = 0; iter < opts.maxIterations; iter++) {
    // main algorithmic loop

    // Update R responsibility matrix
    for (var _i8 = 0; _i8 < n; _i8++) {
      var max = -Infinity,
        max2 = -Infinity,
        maxI = -1,
        AS = 0.0;
      for (var _j = 0; _j < n; _j++) {
        old[_j] = R[_i8 * n + _j];
        AS = A[_i8 * n + _j] + S[_i8 * n + _j];
        if (AS >= max) {
          max2 = max;
          max = AS;
          maxI = _j;
        } else if (AS > max2) {
          max2 = AS;
        }
      }
      for (var _j2 = 0; _j2 < n; _j2++) {
        R[_i8 * n + _j2] = (1 - opts.damping) * (S[_i8 * n + _j2] - max) + opts.damping * old[_j2];
      }
      R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];
    }

    // Update A availability matrix
    for (var _i9 = 0; _i9 < n; _i9++) {
      var sum = 0;
      for (var _j3 = 0; _j3 < n; _j3++) {
        old[_j3] = A[_j3 * n + _i9];
        Rp[_j3] = Math.max(0, R[_j3 * n + _i9]);
        sum += Rp[_j3];
      }
      sum -= Rp[_i9];
      Rp[_i9] = R[_i9 * n + _i9];
      sum += Rp[_i9];
      for (var _j4 = 0; _j4 < n; _j4++) {
        A[_j4 * n + _i9] = (1 - opts.damping) * Math.min(0, sum - Rp[_j4]) + opts.damping * old[_j4];
      }
      A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];
    }

    // Check for convergence
    var K = 0;
    for (var _i10 = 0; _i10 < n; _i10++) {
      var E = A[_i10 * n + _i10] + R[_i10 * n + _i10] > 0 ? 1 : 0;
      e[iter % opts.minIterations * n + _i10] = E;
      K += E;
    }
    if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {
      var _sum = 0;
      for (var _i11 = 0; _i11 < n; _i11++) {
        se[_i11] = 0;
        for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {
          se[_i11] += e[_j5 * n + _i11];
        }
        if (se[_i11] === 0 || se[_i11] === opts.minIterations) {
          _sum++;
        }
      }
      if (_sum === n) {
        // then we have convergence
        break;
      }
    }
  }

  // Identify exemplars (cluster centers)
  var exemplarsIndices = findExemplars(n, R, A);

  // Assign nodes to clusters
  var clusterIndices = assign(n, S, exemplarsIndices);
  var clusters = {};
  for (var c = 0; c < exemplarsIndices.length; c++) {
    clusters[exemplarsIndices[c]] = [];
  }
  for (var _i12 = 0; _i12 < nodes.length; _i12++) {
    var pos = id2position[nodes[_i12].id()];
    var clusterIndex = clusterIndices[pos];
    if (clusterIndex != null) {
      // the node may have not been assigned a cluster if no valid attributes were specified
      clusters[clusterIndex].push(nodes[_i12]);
    }
  }
  var retClusters = new Array(exemplarsIndices.length);
  for (var _c = 0; _c < exemplarsIndices.length; _c++) {
    retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);
  }
  return retClusters;
};
var affinityPropagation$1 = {
  affinityPropagation: affinityPropagation,
  ap: affinityPropagation
};

var hierholzerDefaults = defaults$g({
  root: undefined,
  directed: false
});
var elesfn$k = {
  hierholzer: function hierholzer(options) {
    if (!plainObject(options)) {
      var args = arguments;
      options = {
        root: args[0],
        directed: args[1]
      };
    }
    var _hierholzerDefaults = hierholzerDefaults(options),
      root = _hierholzerDefaults.root,
      directed = _hierholzerDefaults.directed;
    var eles = this;
    var dflag = false;
    var oddIn;
    var oddOut;
    var startVertex;
    if (root) startVertex = string(root) ? this.filter(root)[0].id() : root[0].id();
    var nodes = {};
    var edges = {};
    if (directed) {
      eles.forEach(function (ele) {
        var id = ele.id();
        if (ele.isNode()) {
          var ind = ele.indegree(true);
          var outd = ele.outdegree(true);
          var d1 = ind - outd;
          var d2 = outd - ind;
          if (d1 == 1) {
            if (oddIn) dflag = true;else oddIn = id;
          } else if (d2 == 1) {
            if (oddOut) dflag = true;else oddOut = id;
          } else if (d2 > 1 || d1 > 1) {
            dflag = true;
          }
          nodes[id] = [];
          ele.outgoers().forEach(function (e) {
            if (e.isEdge()) nodes[id].push(e.id());
          });
        } else {
          edges[id] = [undefined, ele.target().id()];
        }
      });
    } else {
      eles.forEach(function (ele) {
        var id = ele.id();
        if (ele.isNode()) {
          var d = ele.degree(true);
          if (d % 2) {
            if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;
          }
          nodes[id] = [];
          ele.connectedEdges().forEach(function (e) {
            return nodes[id].push(e.id());
          });
        } else {
          edges[id] = [ele.source().id(), ele.target().id()];
        }
      });
    }
    var result = {
      found: false,
      trail: undefined
    };
    if (dflag) return result;else if (oddOut && oddIn) {
      if (directed) {
        if (startVertex && oddOut != startVertex) {
          return result;
        }
        startVertex = oddOut;
      } else {
        if (startVertex && oddOut != startVertex && oddIn != startVertex) {
          return result;
        } else if (!startVertex) {
          startVertex = oddOut;
        }
      }
    } else {
      if (!startVertex) startVertex = eles[0].id();
    }
    var walk = function walk(v) {
      var currentNode = v;
      var subtour = [v];
      var adj, adjTail, adjHead;
      while (nodes[currentNode].length) {
        adj = nodes[currentNode].shift();
        adjTail = edges[adj][0];
        adjHead = edges[adj][1];
        if (currentNode != adjHead) {
          nodes[adjHead] = nodes[adjHead].filter(function (e) {
            return e != adj;
          });
          currentNode = adjHead;
        } else if (!directed && currentNode != adjTail) {
          nodes[adjTail] = nodes[adjTail].filter(function (e) {
            return e != adj;
          });
          currentNode = adjTail;
        }
        subtour.unshift(adj);
        subtour.unshift(currentNode);
      }
      return subtour;
    };
    var trail = [];
    var subtour = [];
    subtour = walk(startVertex);
    while (subtour.length != 1) {
      if (nodes[subtour[0]].length == 0) {
        trail.unshift(eles.getElementById(subtour.shift()));
        trail.unshift(eles.getElementById(subtour.shift()));
      } else {
        subtour = walk(subtour.shift()).concat(subtour);
      }
    }
    trail.unshift(eles.getElementById(subtour.shift())); // final node

    for (var d in nodes) {
      if (nodes[d].length) {
        return result;
      }
    }
    result.found = true;
    result.trail = this.spawn(trail, true);
    return result;
  }
};

var hopcroftTarjanBiconnected = function hopcroftTarjanBiconnected() {
  var eles = this;
  var nodes = {};
  var id = 0;
  var edgeCount = 0;
  var components = [];
  var stack = [];
  var visitedEdges = {};
  var buildComponent = function buildComponent(x, y) {
    var i = stack.length - 1;
    var cutset = [];
    var component = eles.spawn();
    while (stack[i].x != x || stack[i].y != y) {
      cutset.push(stack.pop().edge);
      i--;
    }
    cutset.push(stack.pop().edge);
    cutset.forEach(function (edge) {
      var connectedNodes = edge.connectedNodes().intersection(eles);
      component.merge(edge);
      connectedNodes.forEach(function (node) {
        var nodeId = node.id();
        var connectedEdges = node.connectedEdges().intersection(eles);
        component.merge(node);
        if (!nodes[nodeId].cutVertex) {
          component.merge(connectedEdges);
        } else {
          component.merge(connectedEdges.filter(function (edge) {
            return edge.isLoop();
          }));
        }
      });
    });
    components.push(component);
  };
  var _biconnectedSearch = function biconnectedSearch(root, currentNode, parent) {
    if (root === parent) edgeCount += 1;
    nodes[currentNode] = {
      id: id,
      low: id++,
      cutVertex: false
    };
    var edges = eles.getElementById(currentNode).connectedEdges().intersection(eles);
    if (edges.size() === 0) {
      components.push(eles.spawn(eles.getElementById(currentNode)));
    } else {
      var sourceId, targetId, otherNodeId, edgeId;
      edges.forEach(function (edge) {
        sourceId = edge.source().id();
        targetId = edge.target().id();
        otherNodeId = sourceId === currentNode ? targetId : sourceId;
        if (otherNodeId !== parent) {
          edgeId = edge.id();
          if (!visitedEdges[edgeId]) {
            visitedEdges[edgeId] = true;
            stack.push({
              x: currentNode,
              y: otherNodeId,
              edge: edge
            });
          }
          if (!(otherNodeId in nodes)) {
            _biconnectedSearch(root, otherNodeId, currentNode);
            nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].low);
            if (nodes[currentNode].id <= nodes[otherNodeId].low) {
              nodes[currentNode].cutVertex = true;
              buildComponent(currentNode, otherNodeId);
            }
          } else {
            nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].id);
          }
        }
      });
    }
  };
  eles.forEach(function (ele) {
    if (ele.isNode()) {
      var nodeId = ele.id();
      if (!(nodeId in nodes)) {
        edgeCount = 0;
        _biconnectedSearch(nodeId, nodeId);
        nodes[nodeId].cutVertex = edgeCount > 1;
      }
    }
  });
  var cutVertices = Object.keys(nodes).filter(function (id) {
    return nodes[id].cutVertex;
  }).map(function (id) {
    return eles.getElementById(id);
  });
  return {
    cut: eles.spawn(cutVertices),
    components: components
  };
};
var hopcroftTarjanBiconnected$1 = {
  hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,
  htbc: hopcroftTarjanBiconnected,
  htb: hopcroftTarjanBiconnected,
  hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected
};

var tarjanStronglyConnected = function tarjanStronglyConnected() {
  var eles = this;
  var nodes = {};
  var index = 0;
  var components = [];
  var stack = [];
  var cut = eles.spawn(eles);
  var _stronglyConnectedSearch = function stronglyConnectedSearch(sourceNodeId) {
    stack.push(sourceNodeId);
    nodes[sourceNodeId] = {
      index: index,
      low: index++,
      explored: false
    };
    var connectedEdges = eles.getElementById(sourceNodeId).connectedEdges().intersection(eles);
    connectedEdges.forEach(function (edge) {
      var targetNodeId = edge.target().id();
      if (targetNodeId !== sourceNodeId) {
        if (!(targetNodeId in nodes)) {
          _stronglyConnectedSearch(targetNodeId);
        }
        if (!nodes[targetNodeId].explored) {
          nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);
        }
      }
    });
    if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {
      var componentNodes = eles.spawn();
      for (;;) {
        var nodeId = stack.pop();
        componentNodes.merge(eles.getElementById(nodeId));
        nodes[nodeId].low = nodes[sourceNodeId].index;
        nodes[nodeId].explored = true;
        if (nodeId === sourceNodeId) {
          break;
        }
      }
      var componentEdges = componentNodes.edgesWith(componentNodes);
      var component = componentNodes.merge(componentEdges);
      components.push(component);
      cut = cut.difference(component);
    }
  };
  eles.forEach(function (ele) {
    if (ele.isNode()) {
      var nodeId = ele.id();
      if (!(nodeId in nodes)) {
        _stronglyConnectedSearch(nodeId);
      }
    }
  });
  return {
    cut: cut,
    components: components
  };
};
var tarjanStronglyConnected$1 = {
  tarjanStronglyConnected: tarjanStronglyConnected,
  tsc: tarjanStronglyConnected,
  tscc: tarjanStronglyConnected,
  tarjanStronglyConnectedComponents: tarjanStronglyConnected
};

var elesfn$j = {};
[elesfn$v, elesfn$u, elesfn$t, elesfn$s, elesfn$r, elesfn$q, elesfn$p, elesfn$o, elesfn$n, elesfn$m, elesfn$l, markovClustering$1, kClustering, hierarchicalClustering$1, affinityPropagation$1, elesfn$k, hopcroftTarjanBiconnected$1, tarjanStronglyConnected$1].forEach(function (props) {
  extend(elesfn$j, props);
});

/*!
Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
Licensed under The MIT License (http://opensource.org/licenses/MIT)
*/

/*  promise states [Promises/A+ 2.1]  */
var STATE_PENDING = 0; /*  [Promises/A+ 2.1.1]  */
var STATE_FULFILLED = 1; /*  [Promises/A+ 2.1.2]  */
var STATE_REJECTED = 2; /*  [Promises/A+ 2.1.3]  */

/*  promise object constructor  */
var _api = function api(executor) {
  /*  optionally support non-constructor/plain-function call  */
  if (!(this instanceof _api)) return new _api(executor);

  /*  initialize object  */
  this.id = 'Thenable/1.0.7';
  this.state = STATE_PENDING; /*  initial state  */
  this.fulfillValue = undefined; /*  initial value  */ /*  [Promises/A+ 1.3, 2.1.2.2]  */
  this.rejectReason = undefined; /*  initial reason */ /*  [Promises/A+ 1.5, 2.1.3.2]  */
  this.onFulfilled = []; /*  initial handlers  */
  this.onRejected = []; /*  initial handlers  */

  /*  provide optional information-hiding proxy  */
  this.proxy = {
    then: this.then.bind(this)
  };

  /*  support optional executor function  */
  if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
};

/*  promise API methods  */
_api.prototype = {
  /*  promise resolving methods  */
  fulfill: function fulfill(value) {
    return deliver(this, STATE_FULFILLED, 'fulfillValue', value);
  },
  reject: function reject(value) {
    return deliver(this, STATE_REJECTED, 'rejectReason', value);
  },
  /*  "The then Method" [Promises/A+ 1.1, 1.2, 2.2]  */
  then: function then(onFulfilled, onRejected) {
    var curr = this;
    var next = new _api(); /*  [Promises/A+ 2.2.7]  */
    curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill')); /*  [Promises/A+ 2.2.2/2.2.6]  */
    curr.onRejected.push(resolver(onRejected, next, 'reject')); /*  [Promises/A+ 2.2.3/2.2.6]  */
    execute(curr);
    return next.proxy; /*  [Promises/A+ 2.2.7, 3.3]  */
  }
};

/*  deliver an action  */
var deliver = function deliver(curr, state, name, value) {
  if (curr.state === STATE_PENDING) {
    curr.state = state; /*  [Promises/A+ 2.1.2.1, 2.1.3.1]  */
    curr[name] = value; /*  [Promises/A+ 2.1.2.2, 2.1.3.2]  */
    execute(curr);
  }
  return curr;
};

/*  execute all handlers  */
var execute = function execute(curr) {
  if (curr.state === STATE_FULFILLED) execute_handlers(curr, 'onFulfilled', curr.fulfillValue);else if (curr.state === STATE_REJECTED) execute_handlers(curr, 'onRejected', curr.rejectReason);
};

/*  execute particular set of handlers  */
var execute_handlers = function execute_handlers(curr, name, value) {
  /* global setImmediate: true */
  /* global setTimeout: true */

  /*  short-circuit processing  */
  if (curr[name].length === 0) return;

  /*  iterate over all handlers, exactly once  */
  var handlers = curr[name];
  curr[name] = []; /*  [Promises/A+ 2.2.2.3, 2.2.3.3]  */
  var func = function func() {
    for (var i = 0; i < handlers.length; i++) handlers[i](value); /*  [Promises/A+ 2.2.5]  */
  };

  /*  execute procedure asynchronously  */ /*  [Promises/A+ 2.2.4, 3.1]  */
  if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);
};

/*  generate a resolver function  */
var resolver = function resolver(cb, next, method) {
  return function (value) {
    if (typeof cb !== 'function') /*  [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4]  */
      next[method].call(next, value); /*  [Promises/A+ 2.2.7.3, 2.2.7.4]  */else {
      var result;
      try {
        result = cb(value);
      } /*  [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2]  */ catch (e) {
        next.reject(e); /*  [Promises/A+ 2.2.7.2]  */
        return;
      }
      _resolve(next, result); /*  [Promises/A+ 2.2.7.1]  */
    }
  };
};

/*  "Promise Resolution Procedure"  */ /*  [Promises/A+ 2.3]  */
var _resolve = function resolve(promise, x) {
  /*  sanity check arguments  */ /*  [Promises/A+ 2.3.1]  */
  if (promise === x || promise.proxy === x) {
    promise.reject(new TypeError('cannot resolve promise with itself'));
    return;
  }

  /*  surgically check for a "then" method
    (mainly to just call the "getter" of "then" only once)  */
  var then;
  if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {
    try {
      then = x.then;
    } /*  [Promises/A+ 2.3.3.1, 3.5]  */ catch (e) {
      promise.reject(e); /*  [Promises/A+ 2.3.3.2]  */
      return;
    }
  }

  /*  handle own Thenables    [Promises/A+ 2.3.2]
    and similar "thenables" [Promises/A+ 2.3.3]  */
  if (typeof then === 'function') {
    var resolved = false;
    try {
      /*  call retrieved "then" method */ /*  [Promises/A+ 2.3.3.3]  */
      then.call(x, /*  resolvePromise  */ /*  [Promises/A+ 2.3.3.3.1]  */
      function (y) {
        if (resolved) return;
        resolved = true; /*  [Promises/A+ 2.3.3.3.3]  */
        if (y === x) /*  [Promises/A+ 3.6]  */
          promise.reject(new TypeError('circular thenable chain'));else _resolve(promise, y);
      }, /*  rejectPromise  */ /*  [Promises/A+ 2.3.3.3.2]  */
      function (r) {
        if (resolved) return;
        resolved = true; /*  [Promises/A+ 2.3.3.3.3]  */
        promise.reject(r);
      });
    } catch (e) {
      if (!resolved) /*  [Promises/A+ 2.3.3.3.3]  */
        promise.reject(e); /*  [Promises/A+ 2.3.3.3.4]  */
    }
    return;
  }

  /*  handle other values  */
  promise.fulfill(x); /*  [Promises/A+ 2.3.4, 2.3.3.4]  */
};

// so we always have Promise.all()
_api.all = function (ps) {
  return new _api(function (resolveAll, rejectAll) {
    var vals = new Array(ps.length);
    var doneCount = 0;
    var fulfill = function fulfill(i, val) {
      vals[i] = val;
      doneCount++;
      if (doneCount === ps.length) {
        resolveAll(vals);
      }
    };
    for (var i = 0; i < ps.length; i++) {
      (function (i) {
        var p = ps[i];
        var isPromise = p != null && p.then != null;
        if (isPromise) {
          p.then(function (val) {
            fulfill(i, val);
          }, function (err) {
            rejectAll(err);
          });
        } else {
          var val = p;
          fulfill(i, val);
        }
      })(i);
    }
  });
};
_api.resolve = function (val) {
  return new _api(function (resolve, reject) {
    resolve(val);
  });
};
_api.reject = function (val) {
  return new _api(function (resolve, reject) {
    reject(val);
  });
};
var Promise$1 = typeof Promise !== 'undefined' ? Promise : _api; // eslint-disable-line no-undef

var Animation = function Animation(target, opts, opts2) {
  var isCore = core(target);
  var isEle = !isCore;
  var _p = this._private = extend({
    duration: 1000
  }, opts, opts2);
  _p.target = target;
  _p.style = _p.style || _p.css;
  _p.started = false;
  _p.playing = false;
  _p.hooked = false;
  _p.applying = false;
  _p.progress = 0;
  _p.completes = [];
  _p.frames = [];
  if (_p.complete && fn$6(_p.complete)) {
    _p.completes.push(_p.complete);
  }
  if (isEle) {
    var pos = target.position();
    _p.startPosition = _p.startPosition || {
      x: pos.x,
      y: pos.y
    };
    _p.startStyle = _p.startStyle || target.cy().style().getAnimationStartStyle(target, _p.style);
  }
  if (isCore) {
    var pan = target.pan();
    _p.startPan = {
      x: pan.x,
      y: pan.y
    };
    _p.startZoom = target.zoom();
  }

  // for future timeline/animations impl
  this.length = 1;
  this[0] = this;
};
var anifn = Animation.prototype;
extend(anifn, {
  instanceString: function instanceString() {
    return 'animation';
  },
  hook: function hook() {
    var _p = this._private;
    if (!_p.hooked) {
      // add to target's animation queue
      var q;
      var tAni = _p.target._private.animation;
      if (_p.queue) {
        q = tAni.queue;
      } else {
        q = tAni.current;
      }
      q.push(this);

      // add to the animation loop pool
      if (elementOrCollection(_p.target)) {
        _p.target.cy().addToAnimationPool(_p.target);
      }
      _p.hooked = true;
    }
    return this;
  },
  play: function play() {
    var _p = this._private;

    // autorewind
    if (_p.progress === 1) {
      _p.progress = 0;
    }
    _p.playing = true;
    _p.started = false; // needs to be started by animation loop
    _p.stopped = false;
    this.hook();

    // the animation loop will start the animation...

    return this;
  },
  playing: function playing() {
    return this._private.playing;
  },
  apply: function apply() {
    var _p = this._private;
    _p.applying = true;
    _p.started = false; // needs to be started by animation loop
    _p.stopped = false;
    this.hook();

    // the animation loop will apply the animation at this progress

    return this;
  },
  applying: function applying() {
    return this._private.applying;
  },
  pause: function pause() {
    var _p = this._private;
    _p.playing = false;
    _p.started = false;
    return this;
  },
  stop: function stop() {
    var _p = this._private;
    _p.playing = false;
    _p.started = false;
    _p.stopped = true; // to be removed from animation queues

    return this;
  },
  rewind: function rewind() {
    return this.progress(0);
  },
  fastforward: function fastforward() {
    return this.progress(1);
  },
  time: function time(t) {
    var _p = this._private;
    if (t === undefined) {
      return _p.progress * _p.duration;
    } else {
      return this.progress(t / _p.duration);
    }
  },
  progress: function progress(p) {
    var _p = this._private;
    var wasPlaying = _p.playing;
    if (p === undefined) {
      return _p.progress;
    } else {
      if (wasPlaying) {
        this.pause();
      }
      _p.progress = p;
      _p.started = false;
      if (wasPlaying) {
        this.play();
      }
    }
    return this;
  },
  completed: function completed() {
    return this._private.progress === 1;
  },
  reverse: function reverse() {
    var _p = this._private;
    var wasPlaying = _p.playing;
    if (wasPlaying) {
      this.pause();
    }
    _p.progress = 1 - _p.progress;
    _p.started = false;
    var swap = function swap(a, b) {
      var _pa = _p[a];
      if (_pa == null) {
        return;
      }
      _p[a] = _p[b];
      _p[b] = _pa;
    };
    swap('zoom', 'startZoom');
    swap('pan', 'startPan');
    swap('position', 'startPosition');

    // swap styles
    if (_p.style) {
      for (var i = 0; i < _p.style.length; i++) {
        var prop = _p.style[i];
        var name = prop.name;
        var startStyleProp = _p.startStyle[name];
        _p.startStyle[name] = prop;
        _p.style[i] = startStyleProp;
      }
    }
    if (wasPlaying) {
      this.play();
    }
    return this;
  },
  promise: function promise(type) {
    var _p = this._private;
    var arr;
    switch (type) {
      case 'frame':
        arr = _p.frames;
        break;
      default:
      case 'complete':
      case 'completed':
        arr = _p.completes;
    }
    return new Promise$1(function (resolve, reject) {
      arr.push(function () {
        resolve();
      });
    });
  }
});
anifn.complete = anifn.completed;
anifn.run = anifn.play;
anifn.running = anifn.playing;

var define$3 = {
  animated: function animated() {
    return function animatedImpl() {
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
      var cy = this._private.cy || this;
      if (!cy.styleEnabled()) {
        return false;
      }
      var ele = all[0];
      if (ele) {
        return ele._private.animation.current.length > 0;
      }
    };
  },
  // animated

  clearQueue: function clearQueue() {
    return function clearQueueImpl() {
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
      var cy = this._private.cy || this;
      if (!cy.styleEnabled()) {
        return this;
      }
      for (var i = 0; i < all.length; i++) {
        var ele = all[i];
        ele._private.animation.queue = [];
      }
      return this;
    };
  },
  // clearQueue

  delay: function delay() {
    return function delayImpl(time, complete) {
      var cy = this._private.cy || this;
      if (!cy.styleEnabled()) {
        return this;
      }
      return this.animate({
        delay: time,
        duration: time,
        complete: complete
      });
    };
  },
  // delay

  delayAnimation: function delayAnimation() {
    return function delayAnimationImpl(time, complete) {
      var cy = this._private.cy || this;
      if (!cy.styleEnabled()) {
        return this;
      }
      return this.animation({
        delay: time,
        duration: time,
        complete: complete
      });
    };
  },
  // delay

  animation: function animation() {
    return function animationImpl(properties, params) {
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
      var cy = this._private.cy || this;
      var isCore = !selfIsArrayLike;
      var isEles = !isCore;
      if (!cy.styleEnabled()) {
        return this;
      }
      var style = cy.style();
      properties = extend({}, properties, params);
      var propertiesEmpty = Object.keys(properties).length === 0;
      if (propertiesEmpty) {
        return new Animation(all[0], properties); // nothing to animate
      }
      if (properties.duration === undefined) {
        properties.duration = 400;
      }
      switch (properties.duration) {
        case 'slow':
          properties.duration = 600;
          break;
        case 'fast':
          properties.duration = 200;
          break;
      }
      if (isEles) {
        properties.style = style.getPropsList(properties.style || properties.css);
        properties.css = undefined;
      }
      if (isEles && properties.renderedPosition != null) {
        var rpos = properties.renderedPosition;
        var pan = cy.pan();
        var zoom = cy.zoom();
        properties.position = renderedToModelPosition(rpos, zoom, pan);
      }

      // override pan w/ panBy if set
      if (isCore && properties.panBy != null) {
        var panBy = properties.panBy;
        var cyPan = cy.pan();
        properties.pan = {
          x: cyPan.x + panBy.x,
          y: cyPan.y + panBy.y
        };
      }

      // override pan w/ center if set
      var center = properties.center || properties.centre;
      if (isCore && center != null) {
        var centerPan = cy.getCenterPan(center.eles, properties.zoom);
        if (centerPan != null) {
          properties.pan = centerPan;
        }
      }

      // override pan & zoom w/ fit if set
      if (isCore && properties.fit != null) {
        var fit = properties.fit;
        var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);
        if (fitVp != null) {
          properties.pan = fitVp.pan;
          properties.zoom = fitVp.zoom;
        }
      }

      // override zoom (& potentially pan) w/ zoom obj if set
      if (isCore && plainObject(properties.zoom)) {
        var vp = cy.getZoomedViewport(properties.zoom);
        if (vp != null) {
          if (vp.zoomed) {
            properties.zoom = vp.zoom;
          }
          if (vp.panned) {
            properties.pan = vp.pan;
          }
        } else {
          properties.zoom = null; // an inavalid zoom (e.g. no delta) gets automatically destroyed
        }
      }
      return new Animation(all[0], properties);
    };
  },
  // animate

  animate: function animate() {
    return function animateImpl(properties, params) {
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
      var cy = this._private.cy || this;
      if (!cy.styleEnabled()) {
        return this;
      }
      if (params) {
        properties = extend({}, properties, params);
      }

      // manually hook and run the animation
      for (var i = 0; i < all.length; i++) {
        var ele = all[i];
        var queue = ele.animated() && (properties.queue === undefined || properties.queue);
        var ani = ele.animation(properties, queue ? {
          queue: true
        } : undefined);
        ani.play();
      }
      return this; // chaining
    };
  },
  // animate

  stop: function stop() {
    return function stopImpl(clearQueue, jumpToEnd) {
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
      var cy = this._private.cy || this;
      if (!cy.styleEnabled()) {
        return this;
      }
      for (var i = 0; i < all.length; i++) {
        var ele = all[i];
        var _p = ele._private;
        var anis = _p.animation.current;
        for (var j = 0; j < anis.length; j++) {
          var ani = anis[j];
          var ani_p = ani._private;
          if (jumpToEnd) {
            // next iteration of the animation loop, the animation
            // will go straight to the end and be removed
            ani_p.duration = 0;
          }
        }

        // clear the queue of future animations
        if (clearQueue) {
          _p.animation.queue = [];
        }
        if (!jumpToEnd) {
          _p.animation.current = [];
        }
      }

      // we have to notify (the animation loop doesn't do it for us on `stop`)
      cy.notify('draw');
      return this;
    };
  } // stop
}; // define

/**
 * 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_1;
var hasRequiredIsArray;

function requireIsArray () {
	if (hasRequiredIsArray) return isArray_1;
	hasRequiredIsArray = 1;
	var isArray = Array.isArray;

	isArray_1 = isArray;
	return isArray_1;
}

var _isKey;
var hasRequired_isKey;

function require_isKey () {
	if (hasRequired_isKey) return _isKey;
	hasRequired_isKey = 1;
	var isArray = requireIsArray(),
	    isSymbol = requireIsSymbol();

	/** 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));
	}

	_isKey = isKey;
	return _isKey;
}

var isFunction_1;
var hasRequiredIsFunction;

function requireIsFunction () {
	if (hasRequiredIsFunction) return isFunction_1;
	hasRequiredIsFunction = 1;
	var baseGetTag = require_baseGetTag(),
	    isObject = requireIsObject();

	/** `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;
	}

	isFunction_1 = isFunction;
	return isFunction_1;
}

var _coreJsData;
var hasRequired_coreJsData;

function require_coreJsData () {
	if (hasRequired_coreJsData) return _coreJsData;
	hasRequired_coreJsData = 1;
	var root = require_root();

	/** Used to detect overreaching core-js shims. */
	var coreJsData = root['__core-js_shared__'];

	_coreJsData = coreJsData;
	return _coreJsData;
}

var _isMasked;
var hasRequired_isMasked;

function require_isMasked () {
	if (hasRequired_isMasked) return _isMasked;
	hasRequired_isMasked = 1;
	var coreJsData = require_coreJsData();

	/** 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);
	}

	_isMasked = isMasked;
	return _isMasked;
}

/** Used for built-in method references. */

var _toSource;
var hasRequired_toSource;

function require_toSource () {
	if (hasRequired_toSource) return _toSource;
	hasRequired_toSource = 1;
	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 '';
	}

	_toSource = toSource;
	return _toSource;
}

var _baseIsNative;
var hasRequired_baseIsNative;

function require_baseIsNative () {
	if (hasRequired_baseIsNative) return _baseIsNative;
	hasRequired_baseIsNative = 1;
	var isFunction = requireIsFunction(),
	    isMasked = require_isMasked(),
	    isObject = requireIsObject(),
	    toSource = require_toSource();

	/**
	 * 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));
	}

	_baseIsNative = baseIsNative;
	return _baseIsNative;
}

/**
 * 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.
 */

var _getValue;
var hasRequired_getValue;

function require_getValue () {
	if (hasRequired_getValue) return _getValue;
	hasRequired_getValue = 1;
	function getValue(object, key) {
	  return object == null ? undefined : object[key];
	}

	_getValue = getValue;
	return _getValue;
}

var _getNative;
var hasRequired_getNative;

function require_getNative () {
	if (hasRequired_getNative) return _getNative;
	hasRequired_getNative = 1;
	var baseIsNative = require_baseIsNative(),
	    getValue = require_getValue();

	/**
	 * 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;
	}

	_getNative = getNative;
	return _getNative;
}

var _nativeCreate;
var hasRequired_nativeCreate;

function require_nativeCreate () {
	if (hasRequired_nativeCreate) return _nativeCreate;
	hasRequired_nativeCreate = 1;
	var getNative = require_getNative();

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

	_nativeCreate = nativeCreate;
	return _nativeCreate;
}

var _hashClear;
var hasRequired_hashClear;

function require_hashClear () {
	if (hasRequired_hashClear) return _hashClear;
	hasRequired_hashClear = 1;
	var nativeCreate = require_nativeCreate();

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

	_hashClear = hashClear;
	return _hashClear;
}

/**
 * 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`.
 */

var _hashDelete;
var hasRequired_hashDelete;

function require_hashDelete () {
	if (hasRequired_hashDelete) return _hashDelete;
	hasRequired_hashDelete = 1;
	function hashDelete(key) {
	  var result = this.has(key) && delete this.__data__[key];
	  this.size -= result ? 1 : 0;
	  return result;
	}

	_hashDelete = hashDelete;
	return _hashDelete;
}

var _hashGet;
var hasRequired_hashGet;

function require_hashGet () {
	if (hasRequired_hashGet) return _hashGet;
	hasRequired_hashGet = 1;
	var nativeCreate = require_nativeCreate();

	/** 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;
	}

	_hashGet = hashGet;
	return _hashGet;
}

var _hashHas;
var hasRequired_hashHas;

function require_hashHas () {
	if (hasRequired_hashHas) return _hashHas;
	hasRequired_hashHas = 1;
	var nativeCreate = require_nativeCreate();

	/** 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);
	}

	_hashHas = hashHas;
	return _hashHas;
}

var _hashSet;
var hasRequired_hashSet;

function require_hashSet () {
	if (hasRequired_hashSet) return _hashSet;
	hasRequired_hashSet = 1;
	var nativeCreate = require_nativeCreate();

	/** 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;
	}

	_hashSet = hashSet;
	return _hashSet;
}

var _Hash;
var hasRequired_Hash;

function require_Hash () {
	if (hasRequired_Hash) return _Hash;
	hasRequired_Hash = 1;
	var hashClear = require_hashClear(),
	    hashDelete = require_hashDelete(),
	    hashGet = require_hashGet(),
	    hashHas = require_hashHas(),
	    hashSet = require_hashSet();

	/**
	 * 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;

	_Hash = Hash;
	return _Hash;
}

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */

var _listCacheClear;
var hasRequired_listCacheClear;

function require_listCacheClear () {
	if (hasRequired_listCacheClear) return _listCacheClear;
	hasRequired_listCacheClear = 1;
	function listCacheClear() {
	  this.__data__ = [];
	  this.size = 0;
	}

	_listCacheClear = listCacheClear;
	return _listCacheClear;
}

/**
 * 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
 */

var eq_1;
var hasRequiredEq;

function requireEq () {
	if (hasRequiredEq) return eq_1;
	hasRequiredEq = 1;
	function eq(value, other) {
	  return value === other || (value !== value && other !== other);
	}

	eq_1 = eq;
	return eq_1;
}

var _assocIndexOf;
var hasRequired_assocIndexOf;

function require_assocIndexOf () {
	if (hasRequired_assocIndexOf) return _assocIndexOf;
	hasRequired_assocIndexOf = 1;
	var eq = requireEq();

	/**
	 * 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;
	}

	_assocIndexOf = assocIndexOf;
	return _assocIndexOf;
}

var _listCacheDelete;
var hasRequired_listCacheDelete;

function require_listCacheDelete () {
	if (hasRequired_listCacheDelete) return _listCacheDelete;
	hasRequired_listCacheDelete = 1;
	var assocIndexOf = require_assocIndexOf();

	/** 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;
	}

	_listCacheDelete = listCacheDelete;
	return _listCacheDelete;
}

var _listCacheGet;
var hasRequired_listCacheGet;

function require_listCacheGet () {
	if (hasRequired_listCacheGet) return _listCacheGet;
	hasRequired_listCacheGet = 1;
	var assocIndexOf = require_assocIndexOf();

	/**
	 * 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];
	}

	_listCacheGet = listCacheGet;
	return _listCacheGet;
}

var _listCacheHas;
var hasRequired_listCacheHas;

function require_listCacheHas () {
	if (hasRequired_listCacheHas) return _listCacheHas;
	hasRequired_listCacheHas = 1;
	var assocIndexOf = require_assocIndexOf();

	/**
	 * 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;
	}

	_listCacheHas = listCacheHas;
	return _listCacheHas;
}

var _listCacheSet;
var hasRequired_listCacheSet;

function require_listCacheSet () {
	if (hasRequired_listCacheSet) return _listCacheSet;
	hasRequired_listCacheSet = 1;
	var assocIndexOf = require_assocIndexOf();

	/**
	 * 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;
	}

	_listCacheSet = listCacheSet;
	return _listCacheSet;
}

var _ListCache;
var hasRequired_ListCache;

function require_ListCache () {
	if (hasRequired_ListCache) return _ListCache;
	hasRequired_ListCache = 1;
	var listCacheClear = require_listCacheClear(),
	    listCacheDelete = require_listCacheDelete(),
	    listCacheGet = require_listCacheGet(),
	    listCacheHas = require_listCacheHas(),
	    listCacheSet = require_listCacheSet();

	/**
	 * 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;

	_ListCache = ListCache;
	return _ListCache;
}

var _Map;
var hasRequired_Map;

function require_Map () {
	if (hasRequired_Map) return _Map;
	hasRequired_Map = 1;
	var getNative = require_getNative(),
	    root = require_root();

	/* Built-in method references that are verified to be native. */
	var Map = getNative(root, 'Map');

	_Map = Map;
	return _Map;
}

var _mapCacheClear;
var hasRequired_mapCacheClear;

function require_mapCacheClear () {
	if (hasRequired_mapCacheClear) return _mapCacheClear;
	hasRequired_mapCacheClear = 1;
	var Hash = require_Hash(),
	    ListCache = require_ListCache(),
	    Map = require_Map();

	/**
	 * 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
	  };
	}

	_mapCacheClear = mapCacheClear;
	return _mapCacheClear;
}

/**
 * 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`.
 */

var _isKeyable;
var hasRequired_isKeyable;

function require_isKeyable () {
	if (hasRequired_isKeyable) return _isKeyable;
	hasRequired_isKeyable = 1;
	function isKeyable(value) {
	  var type = typeof value;
	  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
	    ? (value !== '__proto__')
	    : (value === null);
	}

	_isKeyable = isKeyable;
	return _isKeyable;
}

var _getMapData;
var hasRequired_getMapData;

function require_getMapData () {
	if (hasRequired_getMapData) return _getMapData;
	hasRequired_getMapData = 1;
	var isKeyable = require_isKeyable();

	/**
	 * 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;
	}

	_getMapData = getMapData;
	return _getMapData;
}

var _mapCacheDelete;
var hasRequired_mapCacheDelete;

function require_mapCacheDelete () {
	if (hasRequired_mapCacheDelete) return _mapCacheDelete;
	hasRequired_mapCacheDelete = 1;
	var getMapData = require_getMapData();

	/**
	 * 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;
	}

	_mapCacheDelete = mapCacheDelete;
	return _mapCacheDelete;
}

var _mapCacheGet;
var hasRequired_mapCacheGet;

function require_mapCacheGet () {
	if (hasRequired_mapCacheGet) return _mapCacheGet;
	hasRequired_mapCacheGet = 1;
	var getMapData = require_getMapData();

	/**
	 * 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);
	}

	_mapCacheGet = mapCacheGet;
	return _mapCacheGet;
}

var _mapCacheHas;
var hasRequired_mapCacheHas;

function require_mapCacheHas () {
	if (hasRequired_mapCacheHas) return _mapCacheHas;
	hasRequired_mapCacheHas = 1;
	var getMapData = require_getMapData();

	/**
	 * 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);
	}

	_mapCacheHas = mapCacheHas;
	return _mapCacheHas;
}

var _mapCacheSet;
var hasRequired_mapCacheSet;

function require_mapCacheSet () {
	if (hasRequired_mapCacheSet) return _mapCacheSet;
	hasRequired_mapCacheSet = 1;
	var getMapData = require_getMapData();

	/**
	 * 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;
	}

	_mapCacheSet = mapCacheSet;
	return _mapCacheSet;
}

var _MapCache;
var hasRequired_MapCache;

function require_MapCache () {
	if (hasRequired_MapCache) return _MapCache;
	hasRequired_MapCache = 1;
	var mapCacheClear = require_mapCacheClear(),
	    mapCacheDelete = require_mapCacheDelete(),
	    mapCacheGet = require_mapCacheGet(),
	    mapCacheHas = require_mapCacheHas(),
	    mapCacheSet = require_mapCacheSet();

	/**
	 * 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;

	_MapCache = MapCache;
	return _MapCache;
}

var memoize_1;
var hasRequiredMemoize;

function requireMemoize () {
	if (hasRequiredMemoize) return memoize_1;
	hasRequiredMemoize = 1;
	var MapCache = require_MapCache();

	/** 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;

	memoize_1 = memoize;
	return memoize_1;
}

var _memoizeCapped;
var hasRequired_memoizeCapped;

function require_memoizeCapped () {
	if (hasRequired_memoizeCapped) return _memoizeCapped;
	hasRequired_memoizeCapped = 1;
	var memoize = requireMemoize();

	/** 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;
	}

	_memoizeCapped = memoizeCapped;
	return _memoizeCapped;
}

var _stringToPath;
var hasRequired_stringToPath;

function require_stringToPath () {
	if (hasRequired_stringToPath) return _stringToPath;
	hasRequired_stringToPath = 1;
	var memoizeCapped = require_memoizeCapped();

	/** 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;
	});

	_stringToPath = stringToPath;
	return _stringToPath;
}

/**
 * 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.
 */

var _arrayMap;
var hasRequired_arrayMap;

function require_arrayMap () {
	if (hasRequired_arrayMap) return _arrayMap;
	hasRequired_arrayMap = 1;
	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;
	}

	_arrayMap = arrayMap;
	return _arrayMap;
}

var _baseToString;
var hasRequired_baseToString;

function require_baseToString () {
	if (hasRequired_baseToString) return _baseToString;
	hasRequired_baseToString = 1;
	var Symbol = require_Symbol(),
	    arrayMap = require_arrayMap(),
	    isArray = requireIsArray(),
	    isSymbol = requireIsSymbol();

	/** 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;
	}

	_baseToString = baseToString;
	return _baseToString;
}

var toString_1;
var hasRequiredToString;

function requireToString () {
	if (hasRequiredToString) return toString_1;
	hasRequiredToString = 1;
	var baseToString = require_baseToString();

	/**
	 * 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);
	}

	toString_1 = toString;
	return toString_1;
}

var _castPath;
var hasRequired_castPath;

function require_castPath () {
	if (hasRequired_castPath) return _castPath;
	hasRequired_castPath = 1;
	var isArray = requireIsArray(),
	    isKey = require_isKey(),
	    stringToPath = require_stringToPath(),
	    toString = requireToString();

	/**
	 * 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));
	}

	_castPath = castPath;
	return _castPath;
}

var _toKey;
var hasRequired_toKey;

function require_toKey () {
	if (hasRequired_toKey) return _toKey;
	hasRequired_toKey = 1;
	var isSymbol = requireIsSymbol();

	/**
	 * 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;
	}

	_toKey = toKey;
	return _toKey;
}

var _baseGet;
var hasRequired_baseGet;

function require_baseGet () {
	if (hasRequired_baseGet) return _baseGet;
	hasRequired_baseGet = 1;
	var castPath = require_castPath(),
	    toKey = require_toKey();

	/**
	 * 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;
	}

	_baseGet = baseGet;
	return _baseGet;
}

var get_1;
var hasRequiredGet;

function requireGet () {
	if (hasRequiredGet) return get_1;
	hasRequiredGet = 1;
	var baseGet = require_baseGet();

	/**
	 * 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;
	}

	get_1 = get;
	return get_1;
}

var getExports = requireGet();
var get = /*@__PURE__*/getDefaultExportFromCjs(getExports);

var _defineProperty;
var hasRequired_defineProperty;

function require_defineProperty () {
	if (hasRequired_defineProperty) return _defineProperty;
	hasRequired_defineProperty = 1;
	var getNative = require_getNative();

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

	_defineProperty = defineProperty;
	return _defineProperty;
}

var _baseAssignValue;
var hasRequired_baseAssignValue;

function require_baseAssignValue () {
	if (hasRequired_baseAssignValue) return _baseAssignValue;
	hasRequired_baseAssignValue = 1;
	var defineProperty = require_defineProperty();

	/**
	 * 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;
	  }
	}

	_baseAssignValue = baseAssignValue;
	return _baseAssignValue;
}

var _assignValue;
var hasRequired_assignValue;

function require_assignValue () {
	if (hasRequired_assignValue) return _assignValue;
	hasRequired_assignValue = 1;
	var baseAssignValue = require_baseAssignValue(),
	    eq = requireEq();

	/** 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);
	  }
	}

	_assignValue = assignValue;
	return _assignValue;
}

/** Used as references for various `Number` constants. */

var _isIndex;
var hasRequired_isIndex;

function require_isIndex () {
	if (hasRequired_isIndex) return _isIndex;
	hasRequired_isIndex = 1;
	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);
	}

	_isIndex = isIndex;
	return _isIndex;
}

var _baseSet;
var hasRequired_baseSet;

function require_baseSet () {
	if (hasRequired_baseSet) return _baseSet;
	hasRequired_baseSet = 1;
	var assignValue = require_assignValue(),
	    castPath = require_castPath(),
	    isIndex = require_isIndex(),
	    isObject = requireIsObject(),
	    toKey = require_toKey();

	/**
	 * 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') {
	      return object;
	    }

	    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;
	}

	_baseSet = baseSet;
	return _baseSet;
}

var set_1;
var hasRequiredSet;

function requireSet () {
	if (hasRequiredSet) return set_1;
	hasRequiredSet = 1;
	var baseSet = require_baseSet();

	/**
	 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
	 * it's created. Arrays are created for missing index properties while objects
	 * are created for all other missing properties. Use `_.setWith` to customize
	 * `path` creation.
	 *
	 * **Note:** This method mutates `object`.
	 *
	 * @static
	 * @memberOf _
	 * @since 3.7.0
	 * @category Object
	 * @param {Object} object The object to modify.
	 * @param {Array|string} path The path of the property to set.
	 * @param {*} value The value to set.
	 * @returns {Object} Returns `object`.
	 * @example
	 *
	 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
	 *
	 * _.set(object, 'a[0].b.c', 4);
	 * console.log(object.a[0].b.c);
	 * // => 4
	 *
	 * _.set(object, ['x', '0', 'y', 'z'], 5);
	 * console.log(object.x[0].y.z);
	 * // => 5
	 */
	function set(object, path, value) {
	  return object == null ? object : baseSet(object, path, value);
	}

	set_1 = set;
	return set_1;
}

var setExports = requireSet();
var set = /*@__PURE__*/getDefaultExportFromCjs(setExports);

/**
 * 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`.
 */

var _copyArray;
var hasRequired_copyArray;

function require_copyArray () {
	if (hasRequired_copyArray) return _copyArray;
	hasRequired_copyArray = 1;
	function copyArray(source, array) {
	  var index = -1,
	      length = source.length;

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

	_copyArray = copyArray;
	return _copyArray;
}

var toPath_1;
var hasRequiredToPath;

function requireToPath () {
	if (hasRequiredToPath) return toPath_1;
	hasRequiredToPath = 1;
	var arrayMap = require_arrayMap(),
	    copyArray = require_copyArray(),
	    isArray = requireIsArray(),
	    isSymbol = requireIsSymbol(),
	    stringToPath = require_stringToPath(),
	    toKey = require_toKey(),
	    toString = requireToString();

	/**
	 * Converts `value` to a property path array.
	 *
	 * @static
	 * @memberOf _
	 * @since 4.0.0
	 * @category Util
	 * @param {*} value The value to convert.
	 * @returns {Array} Returns the new property path array.
	 * @example
	 *
	 * _.toPath('a.b.c');
	 * // => ['a', 'b', 'c']
	 *
	 * _.toPath('a[0].b.c');
	 * // => ['a', '0', 'b', 'c']
	 */
	function toPath(value) {
	  if (isArray(value)) {
	    return arrayMap(value, toKey);
	  }
	  return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
	}

	toPath_1 = toPath;
	return toPath_1;
}

var toPathExports = requireToPath();
var toPath = /*@__PURE__*/getDefaultExportFromCjs(toPathExports);

var define$2 = {
  // access data field
  data: function data(params) {
    var defaults = {
      field: 'data',
      bindingEvent: 'data',
      allowBinding: false,
      allowSetting: false,
      allowGetting: false,
      settingEvent: 'data',
      settingTriggersEvent: false,
      triggerFnName: 'trigger',
      immutableKeys: {},
      // key => true if immutable
      updateStyle: false,
      beforeGet: function beforeGet(self) {},
      beforeSet: function beforeSet(self, obj) {},
      onSet: function onSet(self) {},
      canSet: function canSet(self) {
        return true;
      }
    };
    params = extend({}, defaults, params);
    return function dataImpl(name, value) {
      var p = params;
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
      var single = selfIsArrayLike ? self[0] : self;

      // .data('foo', ...)
      if (string(name)) {
        // set or get property
        var isPathLike = name.indexOf('.') !== -1; // there might be a normal field with a dot 
        var path = isPathLike && toPath(name);

        // .data('foo')
        if (p.allowGetting && value === undefined) {
          // get

          var ret;
          if (single) {
            p.beforeGet(single);

            // check if it's path and a field with the same name doesn't exist
            if (path && single._private[p.field][name] === undefined) {
              ret = get(single._private[p.field], path);
            } else {
              ret = single._private[p.field][name];
            }
          }
          return ret;

          // .data('foo', 'bar')
        } else if (p.allowSetting && value !== undefined) {
          // set
          var valid = !p.immutableKeys[name];
          if (valid) {
            var change = _defineProperty$1({}, name, value);
            p.beforeSet(self, change);
            for (var i = 0, l = all.length; i < l; i++) {
              var ele = all[i];
              if (p.canSet(ele)) {
                if (path && single._private[p.field][name] === undefined) {
                  set(ele._private[p.field], path, value);
                } else {
                  ele._private[p.field][name] = value;
                }
              }
            }

            // update mappers if asked
            if (p.updateStyle) {
              self.updateStyle();
            }

            // call onSet callback
            p.onSet(self);
            if (p.settingTriggersEvent) {
              self[p.triggerFnName](p.settingEvent);
            }
          }
        }

        // .data({ 'foo': 'bar' })
      } else if (p.allowSetting && plainObject(name)) {
        // extend
        var obj = name;
        var k, v;
        var keys = Object.keys(obj);
        p.beforeSet(self, obj);
        for (var _i = 0; _i < keys.length; _i++) {
          k = keys[_i];
          v = obj[k];
          var _valid = !p.immutableKeys[k];
          if (_valid) {
            for (var j = 0; j < all.length; j++) {
              var _ele = all[j];
              if (p.canSet(_ele)) {
                _ele._private[p.field][k] = v;
              }
            }
          }
        }

        // update mappers if asked
        if (p.updateStyle) {
          self.updateStyle();
        }

        // call onSet callback
        p.onSet(self);
        if (p.settingTriggersEvent) {
          self[p.triggerFnName](p.settingEvent);
        }

        // .data(function(){ ... })
      } else if (p.allowBinding && fn$6(name)) {
        // bind to event
        var fn = name;
        self.on(p.bindingEvent, fn);

        // .data()
      } else if (p.allowGetting && name === undefined) {
        // get whole object
        var _ret;
        if (single) {
          p.beforeGet(single);
          _ret = single._private[p.field];
        }
        return _ret;
      }
      return self; // maintain chainability
    }; // function
  },
  // data

  // remove data field
  removeData: function removeData(params) {
    var defaults = {
      field: 'data',
      event: 'data',
      triggerFnName: 'trigger',
      triggerEvent: false,
      immutableKeys: {} // key => true if immutable
    };
    params = extend({}, defaults, params);
    return function removeDataImpl(names) {
      var p = params;
      var self = this;
      var selfIsArrayLike = self.length !== undefined;
      var all = selfIsArrayLike ? self : [self]; // put in array if not array-like

      // .removeData('foo bar')
      if (string(names)) {
        // then get the list of keys, and delete them
        var keys = names.split(/\s+/);
        var l = keys.length;
        for (var i = 0; i < l; i++) {
          // delete each non-empty key
          var key = keys[i];
          if (emptyString(key)) {
            continue;
          }
          var valid = !p.immutableKeys[key]; // not valid if immutable
          if (valid) {
            for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {
              all[i_a]._private[p.field][key] = undefined;
            }
          }
        }
        if (p.triggerEvent) {
          self[p.triggerFnName](p.event);
        }

        // .removeData()
      } else if (names === undefined) {
        // then delete all keys

        for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {
          var _privateFields = all[_i_a]._private[p.field];
          var _keys = Object.keys(_privateFields);
          for (var _i2 = 0; _i2 < _keys.length; _i2++) {
            var _key = _keys[_i2];
            var validKeyToDelete = !p.immutableKeys[_key];
            if (validKeyToDelete) {
              _privateFields[_key] = undefined;
            }
          }
        }
        if (p.triggerEvent) {
          self[p.triggerFnName](p.event);
        }
      }
      return self; // maintain chaining
    }; // function
  } // removeData
}; // define

var define$1 = {
  eventAliasesOn: function eventAliasesOn(proto) {
    var p = proto;
    p.addListener = p.listen = p.bind = p.on;
    p.unlisten = p.unbind = p.off = p.removeListener;
    p.trigger = p.emit;

    // this is just a wrapper alias of .on()
    p.pon = p.promiseOn = function (events, selector) {
      var self = this;
      var args = Array.prototype.slice.call(arguments, 0);
      return new Promise$1(function (resolve, reject) {
        var callback = function callback(e) {
          self.off.apply(self, offArgs);
          resolve(e);
        };
        var onArgs = args.concat([callback]);
        var offArgs = onArgs.concat([]);
        self.on.apply(self, onArgs);
      });
    };
  }
}; // define

// use this module to cherry pick functions into your prototype
// (useful for functions shared between the core and collections, for example)

var define = {};
[define$3, define$2, define$1].forEach(function (m) {
  extend(define, m);
});

var elesfn$i = {
  animate: define.animate(),
  animation: define.animation(),
  animated: define.animated(),
  clearQueue: define.clearQueue(),
  delay: define.delay(),
  delayAnimation: define.delayAnimation(),
  stop: define.stop()
};

var elesfn$h = {
  classes: function classes(_classes) {
    var self = this;
    if (_classes === undefined) {
      var ret = [];
      self[0]._private.classes.forEach(function (cls) {
        return ret.push(cls);
      });
      return ret;
    } else if (!array(_classes)) {
      // extract classes from string
      _classes = (_classes || '').match(/\S+/g) || [];
    }
    var changed = [];
    var classesSet = new Set$1(_classes);

    // check and update each ele
    for (var j = 0; j < self.length; j++) {
      var ele = self[j];
      var _p = ele._private;
      var eleClasses = _p.classes;
      var changedEle = false;

      // check if ele has all of the passed classes
      for (var i = 0; i < _classes.length; i++) {
        var cls = _classes[i];
        var eleHasClass = eleClasses.has(cls);
        if (!eleHasClass) {
          changedEle = true;
          break;
        }
      }

      // check if ele has classes outside of those passed
      if (!changedEle) {
        changedEle = eleClasses.size !== _classes.length;
      }
      if (changedEle) {
        _p.classes = classesSet;
        changed.push(ele);
      }
    }

    // trigger update style on those eles that had class changes
    if (changed.length > 0) {
      this.spawn(changed).updateStyle().emit('class');
    }
    return self;
  },
  addClass: function addClass(classes) {
    return this.toggleClass(classes, true);
  },
  hasClass: function hasClass(className) {
    var ele = this[0];
    return ele != null && ele._private.classes.has(className);
  },
  toggleClass: function toggleClass(classes, toggle) {
    if (!array(classes)) {
      // extract classes from string
      classes = classes.match(/\S+/g) || [];
    }
    var self = this;
    var toggleUndefd = toggle === undefined;
    var changed = []; // eles who had classes changed

    for (var i = 0, il = self.length; i < il; i++) {
      var ele = self[i];
      var eleClasses = ele._private.classes;
      var changedEle = false;
      for (var j = 0; j < classes.length; j++) {
        var cls = classes[j];
        var hasClass = eleClasses.has(cls);
        var changedNow = false;
        if (toggle || toggleUndefd && !hasClass) {
          eleClasses.add(cls);
          changedNow = true;
        } else if (!toggle || toggleUndefd && hasClass) {
          eleClasses["delete"](cls);
          changedNow = true;
        }
        if (!changedEle && changedNow) {
          changed.push(ele);
          changedEle = true;
        }
      } // for j classes
    } // for i eles

    // trigger update style on those eles that had class changes
    if (changed.length > 0) {
      this.spawn(changed).updateStyle().emit('class');
    }
    return self;
  },
  removeClass: function removeClass(classes) {
    return this.toggleClass(classes, false);
  },
  flashClass: function flashClass(classes, duration) {
    var self = this;
    if (duration == null) {
      duration = 250;
    } else if (duration === 0) {
      return self; // nothing to do really
    }
    self.addClass(classes);
    setTimeout(function () {
      self.removeClass(classes);
    }, duration);
    return self;
  }
};
elesfn$h.className = elesfn$h.classNames = elesfn$h.classes;

// tokens in the query language
var tokens = {
  metaChar: '[\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]',
  // chars we need to escape in let names, etc
  comparatorOp: '=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=',
  // binary comparison op (used in data selectors)
  boolOp: '\\?|\\!|\\^',
  // boolean (unary) operators (used in data selectors)
  string: '"(?:\\\\"|[^"])*"' + '|' + "'(?:\\\\'|[^'])*'",
  // string literals (used in data selectors) -- doublequotes | singlequotes
  number: number,
  // number literal (used in data selectors) --- e.g. 0.1234, 1234, 12e123
  meta: 'degree|indegree|outdegree',
  // allowed metadata fields (i.e. allowed functions to use from Collection)
  separator: '\\s*,\\s*',
  // queries are separated by commas, e.g. edge[foo = 'bar'], node.someClass
  descendant: '\\s+',
  child: '\\s+>\\s+',
  subject: '\\$',
  group: 'node|edge|\\*',
  directedEdge: '\\s+->\\s+',
  undirectedEdge: '\\s+<->\\s+'
};
tokens.variable = '(?:[\\w-.]|(?:\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods
tokens.className = '(?:[\\w-]|(?:\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name
tokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number
tokens.id = tokens.variable; // an element id (follows variable conventions)

(function () {
  var ops, op, i;

  // add @ variants to comparatorOp
  ops = tokens.comparatorOp.split('|');
  for (i = 0; i < ops.length; i++) {
    op = ops[i];
    tokens.comparatorOp += '|@' + op;
  }

  // add ! variants to comparatorOp
  ops = tokens.comparatorOp.split('|');
  for (i = 0; i < ops.length; i++) {
    op = ops[i];
    if (op.indexOf('!') >= 0) {
      continue;
    } // skip ops that explicitly contain !
    if (op === '=') {
      continue;
    } // skip = b/c != is explicitly defined

    tokens.comparatorOp += '|\\!' + op;
  }
})();

/**
 * Make a new query object
 *
 * @prop type {Type} The type enum (int) of the query
 * @prop checks List of checks to make against an ele to test for a match
 */
var newQuery = function newQuery() {
  return {
    checks: []
  };
};

/**
 * A check type enum-like object.  Uses integer values for fast match() lookup.
 * The ordering does not matter as long as the ints are unique.
 */
var Type = {
  /** E.g. node */
  GROUP: 0,
  /** A collection of elements */
  COLLECTION: 1,
  /** A filter(ele) function */
  FILTER: 2,
  /** E.g. [foo > 1] */
  DATA_COMPARE: 3,
  /** E.g. [foo] */
  DATA_EXIST: 4,
  /** E.g. [?foo] */
  DATA_BOOL: 5,
  /** E.g. [[degree > 2]] */
  META_COMPARE: 6,
  /** E.g. :selected */
  STATE: 7,
  /** E.g. #foo */
  ID: 8,
  /** E.g. .foo */
  CLASS: 9,
  /** E.g. #foo <-> #bar */
  UNDIRECTED_EDGE: 10,
  /** E.g. #foo -> #bar */
  DIRECTED_EDGE: 11,
  /** E.g. $#foo -> #bar */
  NODE_SOURCE: 12,
  /** E.g. #foo -> $#bar */
  NODE_TARGET: 13,
  /** E.g. $#foo <-> #bar */
  NODE_NEIGHBOR: 14,
  /** E.g. #foo > #bar */
  CHILD: 15,
  /** E.g. #foo #bar */
  DESCENDANT: 16,
  /** E.g. $#foo > #bar */
  PARENT: 17,
  /** E.g. $#foo #bar */
  ANCESTOR: 18,
  /** E.g. #foo > $bar > #baz */
  COMPOUND_SPLIT: 19,
  /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */
  TRUE: 20
};

var stateSelectors = [{
  selector: ':selected',
  matches: function matches(ele) {
    return ele.selected();
  }
}, {
  selector: ':unselected',
  matches: function matches(ele) {
    return !ele.selected();
  }
}, {
  selector: ':selectable',
  matches: function matches(ele) {
    return ele.selectable();
  }
}, {
  selector: ':unselectable',
  matches: function matches(ele) {
    return !ele.selectable();
  }
}, {
  selector: ':locked',
  matches: function matches(ele) {
    return ele.locked();
  }
}, {
  selector: ':unlocked',
  matches: function matches(ele) {
    return !ele.locked();
  }
}, {
  selector: ':visible',
  matches: function matches(ele) {
    return ele.visible();
  }
}, {
  selector: ':hidden',
  matches: function matches(ele) {
    return !ele.visible();
  }
}, {
  selector: ':transparent',
  matches: function matches(ele) {
    return ele.transparent();
  }
}, {
  selector: ':grabbed',
  matches: function matches(ele) {
    return ele.grabbed();
  }
}, {
  selector: ':free',
  matches: function matches(ele) {
    return !ele.grabbed();
  }
}, {
  selector: ':removed',
  matches: function matches(ele) {
    return ele.removed();
  }
}, {
  selector: ':inside',
  matches: function matches(ele) {
    return !ele.removed();
  }
}, {
  selector: ':grabbable',
  matches: function matches(ele) {
    return ele.grabbable();
  }
}, {
  selector: ':ungrabbable',
  matches: function matches(ele) {
    return !ele.grabbable();
  }
}, {
  selector: ':animated',
  matches: function matches(ele) {
    return ele.animated();
  }
}, {
  selector: ':unanimated',
  matches: function matches(ele) {
    return !ele.animated();
  }
}, {
  selector: ':parent',
  matches: function matches(ele) {
    return ele.isParent();
  }
}, {
  selector: ':childless',
  matches: function matches(ele) {
    return ele.isChildless();
  }
}, {
  selector: ':child',
  matches: function matches(ele) {
    return ele.isChild();
  }
}, {
  selector: ':orphan',
  matches: function matches(ele) {
    return ele.isOrphan();
  }
}, {
  selector: ':nonorphan',
  matches: function matches(ele) {
    return ele.isChild();
  }
}, {
  selector: ':compound',
  matches: function matches(ele) {
    if (ele.isNode()) {
      return ele.isParent();
    } else {
      return ele.source().isParent() || ele.target().isParent();
    }
  }
}, {
  selector: ':loop',
  matches: function matches(ele) {
    return ele.isLoop();
  }
}, {
  selector: ':simple',
  matches: function matches(ele) {
    return ele.isSimple();
  }
}, {
  selector: ':active',
  matches: function matches(ele) {
    return ele.active();
  }
}, {
  selector: ':inactive',
  matches: function matches(ele) {
    return !ele.active();
  }
}, {
  selector: ':backgrounding',
  matches: function matches(ele) {
    return ele.backgrounding();
  }
}, {
  selector: ':nonbackgrounding',
  matches: function matches(ele) {
    return !ele.backgrounding();
  }
}].sort(function (a, b) {
  // n.b. selectors that are starting substrings of others must have the longer ones first
  return descending(a.selector, b.selector);
});
var lookup = function () {
  var selToFn = {};
  var s;
  for (var i = 0; i < stateSelectors.length; i++) {
    s = stateSelectors[i];
    selToFn[s.selector] = s.matches;
  }
  return selToFn;
}();
var stateSelectorMatches = function stateSelectorMatches(sel, ele) {
  return lookup[sel](ele);
};
var stateSelectorRegex = '(' + stateSelectors.map(function (s) {
  return s.selector;
}).join('|') + ')';

// when a token like a variable has escaped meta characters, we need to clean the backslashes out
// so that values get compared properly in Selector.filter()
var cleanMetaChars = function cleanMetaChars(str) {
  return str.replace(new RegExp('\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {
    return $1;
  });
};
var replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {
  selector[selector.length - 1] = replacementQuery;
};

// NOTE: add new expression syntax here to have it recognised by the parser;
// - a query contains all adjacent (i.e. no separator in between) expressions;
// - the current query is stored in selector[i]
// - you need to check the query objects in match() for it actually filter properly, but that's pretty straight forward
var exprs = [{
  name: 'group',
  // just used for identifying when debugging
  query: true,
  regex: '(' + tokens.group + ')',
  populate: function populate(selector, query, _ref) {
    var _ref2 = _slicedToArray(_ref, 1),
      group = _ref2[0];
    query.checks.push({
      type: Type.GROUP,
      value: group === '*' ? group : group + 's'
    });
  }
}, {
  name: 'state',
  query: true,
  regex: stateSelectorRegex,
  populate: function populate(selector, query, _ref3) {
    var _ref4 = _slicedToArray(_ref3, 1),
      state = _ref4[0];
    query.checks.push({
      type: Type.STATE,
      value: state
    });
  }
}, {
  name: 'id',
  query: true,
  regex: '\\#(' + tokens.id + ')',
  populate: function populate(selector, query, _ref5) {
    var _ref6 = _slicedToArray(_ref5, 1),
      id = _ref6[0];
    query.checks.push({
      type: Type.ID,
      value: cleanMetaChars(id)
    });
  }
}, {
  name: 'className',
  query: true,
  regex: '\\.(' + tokens.className + ')',
  populate: function populate(selector, query, _ref7) {
    var _ref8 = _slicedToArray(_ref7, 1),
      className = _ref8[0];
    query.checks.push({
      type: Type.CLASS,
      value: cleanMetaChars(className)
    });
  }
}, {
  name: 'dataExists',
  query: true,
  regex: '\\[\\s*(' + tokens.variable + ')\\s*\\]',
  populate: function populate(selector, query, _ref9) {
    var _ref10 = _slicedToArray(_ref9, 1),
      variable = _ref10[0];
    query.checks.push({
      type: Type.DATA_EXIST,
      field: cleanMetaChars(variable)
    });
  }
}, {
  name: 'dataCompare',
  query: true,
  regex: '\\[\\s*(' + tokens.variable + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.value + ')\\s*\\]',
  populate: function populate(selector, query, _ref11) {
    var _ref12 = _slicedToArray(_ref11, 3),
      variable = _ref12[0],
      comparatorOp = _ref12[1],
      value = _ref12[2];
    var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;
    if (valueIsString) {
      value = value.substring(1, value.length - 1);
    } else {
      value = parseFloat(value);
    }
    query.checks.push({
      type: Type.DATA_COMPARE,
      field: cleanMetaChars(variable),
      operator: comparatorOp,
      value: value
    });
  }
}, {
  name: 'dataBool',
  query: true,
  regex: '\\[\\s*(' + tokens.boolOp + ')\\s*(' + tokens.variable + ')\\s*\\]',
  populate: function populate(selector, query, _ref13) {
    var _ref14 = _slicedToArray(_ref13, 2),
      boolOp = _ref14[0],
      variable = _ref14[1];
    query.checks.push({
      type: Type.DATA_BOOL,
      field: cleanMetaChars(variable),
      operator: boolOp
    });
  }
}, {
  name: 'metaCompare',
  query: true,
  regex: '\\[\\[\\s*(' + tokens.meta + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.number + ')\\s*\\]\\]',
  populate: function populate(selector, query, _ref15) {
    var _ref16 = _slicedToArray(_ref15, 3),
      meta = _ref16[0],
      comparatorOp = _ref16[1],
      number = _ref16[2];
    query.checks.push({
      type: Type.META_COMPARE,
      field: cleanMetaChars(meta),
      operator: comparatorOp,
      value: parseFloat(number)
    });
  }
}, {
  name: 'nextQuery',
  separator: true,
  regex: tokens.separator,
  populate: function populate(selector, query) {
    var currentSubject = selector.currentSubject;
    var edgeCount = selector.edgeCount;
    var compoundCount = selector.compoundCount;
    var lastQ = selector[selector.length - 1];
    if (currentSubject != null) {
      lastQ.subject = currentSubject;
      selector.currentSubject = null;
    }
    lastQ.edgeCount = edgeCount;
    lastQ.compoundCount = compoundCount;
    selector.edgeCount = 0;
    selector.compoundCount = 0;

    // go on to next query
    var nextQuery = selector[selector.length++] = newQuery();
    return nextQuery; // this is the new query to be filled by the following exprs
  }
}, {
  name: 'directedEdge',
  separator: true,
  regex: tokens.directedEdge,
  populate: function populate(selector, query) {
    if (selector.currentSubject == null) {
      // undirected edge
      var edgeQuery = newQuery();
      var source = query;
      var target = newQuery();
      edgeQuery.checks.push({
        type: Type.DIRECTED_EDGE,
        source: source,
        target: target
      });

      // the query in the selector should be the edge rather than the source
      replaceLastQuery(selector, query, edgeQuery);
      selector.edgeCount++;

      // we're now populating the target query with expressions that follow
      return target;
    } else {
      // source/target
      var srcTgtQ = newQuery();
      var _source = query;
      var _target = newQuery();
      srcTgtQ.checks.push({
        type: Type.NODE_SOURCE,
        source: _source,
        target: _target
      });

      // the query in the selector should be the neighbourhood rather than the node
      replaceLastQuery(selector, query, srcTgtQ);
      selector.edgeCount++;
      return _target; // now populating the target with the following expressions
    }
  }
}, {
  name: 'undirectedEdge',
  separator: true,
  regex: tokens.undirectedEdge,
  populate: function populate(selector, query) {
    if (selector.currentSubject == null) {
      // undirected edge
      var edgeQuery = newQuery();
      var source = query;
      var target = newQuery();
      edgeQuery.checks.push({
        type: Type.UNDIRECTED_EDGE,
        nodes: [source, target]
      });

      // the query in the selector should be the edge rather than the source
      replaceLastQuery(selector, query, edgeQuery);
      selector.edgeCount++;

      // we're now populating the target query with expressions that follow
      return target;
    } else {
      // neighbourhood
      var nhoodQ = newQuery();
      var node = query;
      var neighbor = newQuery();
      nhoodQ.checks.push({
        type: Type.NODE_NEIGHBOR,
        node: node,
        neighbor: neighbor
      });

      // the query in the selector should be the neighbourhood rather than the node
      replaceLastQuery(selector, query, nhoodQ);
      return neighbor; // now populating the neighbor with following expressions
    }
  }
}, {
  name: 'child',
  separator: true,
  regex: tokens.child,
  populate: function populate(selector, query) {
    if (selector.currentSubject == null) {
      // default: child query
      var parentChildQuery = newQuery();
      var child = newQuery();
      var parent = selector[selector.length - 1];
      parentChildQuery.checks.push({
        type: Type.CHILD,
        parent: parent,
        child: child
      });

      // the query in the selector should be the '>' itself
      replaceLastQuery(selector, query, parentChildQuery);
      selector.compoundCount++;

      // we're now populating the child query with expressions that follow
      return child;
    } else if (selector.currentSubject === query) {
      // compound split query
      var compound = newQuery();
      var left = selector[selector.length - 1];
      var right = newQuery();
      var subject = newQuery();
      var _child = newQuery();
      var _parent = newQuery();

      // set up the root compound q
      compound.checks.push({
        type: Type.COMPOUND_SPLIT,
        left: left,
        right: right,
        subject: subject
      });

      // populate the subject and replace the q at the old spot (within left) with TRUE
      subject.checks = query.checks; // take the checks from the left
      query.checks = [{
        type: Type.TRUE
      }]; // checks under left refs the subject implicitly

      // set up the right q
      _parent.checks.push({
        type: Type.TRUE
      }); // parent implicitly refs the subject
      right.checks.push({
        type: Type.PARENT,
        // type is swapped on right side queries
        parent: _parent,
        child: _child // empty for now
      });
      replaceLastQuery(selector, left, compound);

      // update the ref since we moved things around for `query`
      selector.currentSubject = subject;
      selector.compoundCount++;
      return _child; // now populating the right side's child
    } else {
      // parent query
      // info for parent query
      var _parent2 = newQuery();
      var _child2 = newQuery();
      var pcQChecks = [{
        type: Type.PARENT,
        parent: _parent2,
        child: _child2
      }];

      // the parent-child query takes the place of the query previously being populated
      _parent2.checks = query.checks; // the previous query contains the checks for the parent
      query.checks = pcQChecks; // pc query takes over

      selector.compoundCount++;
      return _child2; // we're now populating the child
    }
  }
}, {
  name: 'descendant',
  separator: true,
  regex: tokens.descendant,
  populate: function populate(selector, query) {
    if (selector.currentSubject == null) {
      // default: descendant query
      var ancChQuery = newQuery();
      var descendant = newQuery();
      var ancestor = selector[selector.length - 1];
      ancChQuery.checks.push({
        type: Type.DESCENDANT,
        ancestor: ancestor,
        descendant: descendant
      });

      // the query in the selector should be the '>' itself
      replaceLastQuery(selector, query, ancChQuery);
      selector.compoundCount++;

      // we're now populating the descendant query with expressions that follow
      return descendant;
    } else if (selector.currentSubject === query) {
      // compound split query
      var compound = newQuery();
      var left = selector[selector.length - 1];
      var right = newQuery();
      var subject = newQuery();
      var _descendant = newQuery();
      var _ancestor = newQuery();

      // set up the root compound q
      compound.checks.push({
        type: Type.COMPOUND_SPLIT,
        left: left,
        right: right,
        subject: subject
      });

      // populate the subject and replace the q at the old spot (within left) with TRUE
      subject.checks = query.checks; // take the checks from the left
      query.checks = [{
        type: Type.TRUE
      }]; // checks under left refs the subject implicitly

      // set up the right q
      _ancestor.checks.push({
        type: Type.TRUE
      }); // ancestor implicitly refs the subject
      right.checks.push({
        type: Type.ANCESTOR,
        // type is swapped on right side queries
        ancestor: _ancestor,
        descendant: _descendant // empty for now
      });
      replaceLastQuery(selector, left, compound);

      // update the ref since we moved things around for `query`
      selector.currentSubject = subject;
      selector.compoundCount++;
      return _descendant; // now populating the right side's descendant
    } else {
      // ancestor query
      // info for parent query
      var _ancestor2 = newQuery();
      var _descendant2 = newQuery();
      var adQChecks = [{
        type: Type.ANCESTOR,
        ancestor: _ancestor2,
        descendant: _descendant2
      }];

      // the parent-child query takes the place of the query previously being populated
      _ancestor2.checks = query.checks; // the previous query contains the checks for the parent
      query.checks = adQChecks; // pc query takes over

      selector.compoundCount++;
      return _descendant2; // we're now populating the child
    }
  }
}, {
  name: 'subject',
  modifier: true,
  regex: tokens.subject,
  populate: function populate(selector, query) {
    if (selector.currentSubject != null && selector.currentSubject !== query) {
      warn('Redefinition of subject in selector `' + selector.toString() + '`');
      return false;
    }
    selector.currentSubject = query;
    var topQ = selector[selector.length - 1];
    var topChk = topQ.checks[0];
    var topType = topChk == null ? null : topChk.type;
    if (topType === Type.DIRECTED_EDGE) {
      // directed edge with subject on the target

      // change to target node check
      topChk.type = Type.NODE_TARGET;
    } else if (topType === Type.UNDIRECTED_EDGE) {
      // undirected edge with subject on the second node

      // change to neighbor check
      topChk.type = Type.NODE_NEIGHBOR;
      topChk.node = topChk.nodes[1]; // second node is subject
      topChk.neighbor = topChk.nodes[0];

      // clean up unused fields for new type
      topChk.nodes = null;
    }
  }
}];
exprs.forEach(function (e) {
  return e.regexObj = new RegExp('^' + e.regex);
});

/**
 * Of all the expressions, find the first match in the remaining text.
 * @param {string} remaining The remaining text to parse
 * @returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`
 */
var consumeExpr = function consumeExpr(remaining) {
  var expr;
  var match;
  var name;
  for (var j = 0; j < exprs.length; j++) {
    var e = exprs[j];
    var n = e.name;
    var m = remaining.match(e.regexObj);
    if (m != null) {
      match = m;
      expr = e;
      name = n;
      var consumed = m[0];
      remaining = remaining.substring(consumed.length);
      break; // we've consumed one expr, so we can return now
    }
  }
  return {
    expr: expr,
    match: match,
    name: name,
    remaining: remaining
  };
};

/**
 * Consume all the leading whitespace
 * @param {string} remaining The text to consume
 * @returns The text with the leading whitespace removed
 */
var consumeWhitespace = function consumeWhitespace(remaining) {
  var match = remaining.match(/^\s+/);
  if (match) {
    var consumed = match[0];
    remaining = remaining.substring(consumed.length);
  }
  return remaining;
};

/**
 * Parse the string and store the parsed representation in the Selector.
 * @param {string} selector The selector string
 * @returns `true` if the selector was successfully parsed, `false` otherwise
 */
var parse = function parse(selector) {
  var self = this;
  var remaining = self.inputText = selector;
  var currentQuery = self[0] = newQuery();
  self.length = 1;
  remaining = consumeWhitespace(remaining); // get rid of leading whitespace

  for (;;) {
    var exprInfo = consumeExpr(remaining);
    if (exprInfo.expr == null) {
      warn('The selector `' + selector + '`is invalid');
      return false;
    } else {
      var args = exprInfo.match.slice(1);

      // let the token populate the selector object in currentQuery
      var ret = exprInfo.expr.populate(self, currentQuery, args);
      if (ret === false) {
        return false; // exit if population failed
      } else if (ret != null) {
        currentQuery = ret; // change the current query to be filled if the expr specifies
      }
    }
    remaining = exprInfo.remaining;

    // we're done when there's nothing left to parse
    if (remaining.match(/^\s*$/)) {
      break;
    }
  }
  var lastQ = self[self.length - 1];
  if (self.currentSubject != null) {
    lastQ.subject = self.currentSubject;
  }
  lastQ.edgeCount = self.edgeCount;
  lastQ.compoundCount = self.compoundCount;
  for (var i = 0; i < self.length; i++) {
    var q = self[i];

    // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations
    if (q.compoundCount > 0 && q.edgeCount > 0) {
      warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');
      return false;
    }
    if (q.edgeCount > 1) {
      warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');
      return false;
    } else if (q.edgeCount === 1) {
      warn('The selector `' + selector + '` is deprecated.  Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons.  Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.');
    }
  }
  return true; // success
};

/**
 * Get the selector represented as a string.  This value uses default formatting,
 * so things like spacing may differ from the input text passed to the constructor.
 * @returns {string} The selector string
 */
var toString = function toString() {
  if (this.toStringCache != null) {
    return this.toStringCache;
  }
  var clean = function clean(obj) {
    if (obj == null) {
      return '';
    } else {
      return obj;
    }
  };
  var cleanVal = function cleanVal(val) {
    if (string(val)) {
      return '"' + val + '"';
    } else {
      return clean(val);
    }
  };
  var space = function space(val) {
    return ' ' + val + ' ';
  };
  var checkToString = function checkToString(check, subject) {
    var type = check.type,
      value = check.value;
    switch (type) {
      case Type.GROUP:
        {
          var group = clean(value);
          return group.substring(0, group.length - 1);
        }
      case Type.DATA_COMPARE:
        {
          var field = check.field,
            operator = check.operator;
          return '[' + field + space(clean(operator)) + cleanVal(value) + ']';
        }
      case Type.DATA_BOOL:
        {
          var _operator = check.operator,
            _field = check.field;
          return '[' + clean(_operator) + _field + ']';
        }
      case Type.DATA_EXIST:
        {
          var _field2 = check.field;
          return '[' + _field2 + ']';
        }
      case Type.META_COMPARE:
        {
          var _operator2 = check.operator,
            _field3 = check.field;
          return '[[' + _field3 + space(clean(_operator2)) + cleanVal(value) + ']]';
        }
      case Type.STATE:
        {
          return value;
        }
      case Type.ID:
        {
          return '#' + value;
        }
      case Type.CLASS:
        {
          return '.' + value;
        }
      case Type.PARENT:
      case Type.CHILD:
        {
          return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);
        }
      case Type.ANCESTOR:
      case Type.DESCENDANT:
        {
          return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);
        }
      case Type.COMPOUND_SPLIT:
        {
          var lhs = queryToString(check.left, subject);
          var sub = queryToString(check.subject, subject);
          var rhs = queryToString(check.right, subject);
          return lhs + (lhs.length > 0 ? ' ' : '') + sub + rhs;
        }
      case Type.TRUE:
        {
          return '';
        }
    }
  };
  var queryToString = function queryToString(query, subject) {
    return query.checks.reduce(function (str, chk, i) {
      return str + (subject === query && i === 0 ? '$' : '') + checkToString(chk, subject);
    }, '');
  };
  var str = '';
  for (var i = 0; i < this.length; i++) {
    var query = this[i];
    str += queryToString(query, query.subject);
    if (this.length > 1 && i < this.length - 1) {
      str += ', ';
    }
  }
  this.toStringCache = str;
  return str;
};
var parse$1 = {
  parse: parse,
  toString: toString
};

var valCmp = function valCmp(fieldVal, operator, value) {
  var matches;
  var isFieldStr = string(fieldVal);
  var isFieldNum = number$1(fieldVal);
  var isValStr = string(value);
  var fieldStr, valStr;
  var caseInsensitive = false;
  var notExpr = false;
  var isIneqCmp = false;
  if (operator.indexOf('!') >= 0) {
    operator = operator.replace('!', '');
    notExpr = true;
  }
  if (operator.indexOf('@') >= 0) {
    operator = operator.replace('@', '');
    caseInsensitive = true;
  }
  if (isFieldStr || isValStr || caseInsensitive) {
    fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;
    valStr = '' + value;
  }

  // if we're doing a case insensitive comparison, then we're using a STRING comparison
  // even if we're comparing numbers
  if (caseInsensitive) {
    fieldVal = fieldStr = fieldStr.toLowerCase();
    value = valStr = valStr.toLowerCase();
  }
  switch (operator) {
    case '*=':
      matches = fieldStr.indexOf(valStr) >= 0;
      break;
    case '$=':
      matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;
      break;
    case '^=':
      matches = fieldStr.indexOf(valStr) === 0;
      break;
    case '=':
      matches = fieldVal === value;
      break;
    case '>':
      isIneqCmp = true;
      matches = fieldVal > value;
      break;
    case '>=':
      isIneqCmp = true;
      matches = fieldVal >= value;
      break;
    case '<':
      isIneqCmp = true;
      matches = fieldVal < value;
      break;
    case '<=':
      isIneqCmp = true;
      matches = fieldVal <= value;
      break;
    default:
      matches = false;
      break;
  }

  // apply the not op, but null vals for inequalities should always stay non-matching
  if (notExpr && (fieldVal != null || !isIneqCmp)) {
    matches = !matches;
  }
  return matches;
};
var boolCmp = function boolCmp(fieldVal, operator) {
  switch (operator) {
    case '?':
      return fieldVal ? true : false;
    case '!':
      return fieldVal ? false : true;
    case '^':
      return fieldVal === undefined;
  }
};
var existCmp = function existCmp(fieldVal) {
  return fieldVal !== undefined;
};
var data$1 = function data(ele, field) {
  return ele.data(field);
};
var meta = function meta(ele, field) {
  return ele[field]();
};

/** A lookup of `match(check, ele)` functions by `Type` int */
var match = [];

/**
 * Returns whether the query matches for the element
 * @param query The `{ type, value, ... }` query object
 * @param ele The element to compare against
*/
var matches$1 = function matches(query, ele) {
  return query.checks.every(function (chk) {
    return match[chk.type](chk, ele);
  });
};
match[Type.GROUP] = function (check, ele) {
  var group = check.value;
  return group === '*' || group === ele.group();
};
match[Type.STATE] = function (check, ele) {
  var stateSelector = check.value;
  return stateSelectorMatches(stateSelector, ele);
};
match[Type.ID] = function (check, ele) {
  var id = check.value;
  return ele.id() === id;
};
match[Type.CLASS] = function (check, ele) {
  var cls = check.value;
  return ele.hasClass(cls);
};
match[Type.META_COMPARE] = function (check, ele) {
  var field = check.field,
    operator = check.operator,
    value = check.value;
  return valCmp(meta(ele, field), operator, value);
};
match[Type.DATA_COMPARE] = function (check, ele) {
  var field = check.field,
    operator = check.operator,
    value = check.value;
  return valCmp(data$1(ele, field), operator, value);
};
match[Type.DATA_BOOL] = function (check, ele) {
  var field = check.field,
    operator = check.operator;
  return boolCmp(data$1(ele, field), operator);
};
match[Type.DATA_EXIST] = function (check, ele) {
  var field = check.field;
    check.operator;
  return existCmp(data$1(ele, field));
};
match[Type.UNDIRECTED_EDGE] = function (check, ele) {
  var qA = check.nodes[0];
  var qB = check.nodes[1];
  var src = ele.source();
  var tgt = ele.target();
  return matches$1(qA, src) && matches$1(qB, tgt) || matches$1(qB, src) && matches$1(qA, tgt);
};
match[Type.NODE_NEIGHBOR] = function (check, ele) {
  return matches$1(check.node, ele) && ele.neighborhood().some(function (n) {
    return n.isNode() && matches$1(check.neighbor, n);
  });
};
match[Type.DIRECTED_EDGE] = function (check, ele) {
  return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());
};
match[Type.NODE_SOURCE] = function (check, ele) {
  return matches$1(check.source, ele) && ele.outgoers().some(function (n) {
    return n.isNode() && matches$1(check.target, n);
  });
};
match[Type.NODE_TARGET] = function (check, ele) {
  return matches$1(check.target, ele) && ele.incomers().some(function (n) {
    return n.isNode() && matches$1(check.source, n);
  });
};
match[Type.CHILD] = function (check, ele) {
  return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());
};
match[Type.PARENT] = function (check, ele) {
  return matches$1(check.parent, ele) && ele.children().some(function (c) {
    return matches$1(check.child, c);
  });
};
match[Type.DESCENDANT] = function (check, ele) {
  return matches$1(check.descendant, ele) && ele.ancestors().some(function (a) {
    return matches$1(check.ancestor, a);
  });
};
match[Type.ANCESTOR] = function (check, ele) {
  return matches$1(check.ancestor, ele) && ele.descendants().some(function (d) {
    return matches$1(check.descendant, d);
  });
};
match[Type.COMPOUND_SPLIT] = function (check, ele) {
  return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);
};
match[Type.TRUE] = function () {
  return true;
};
match[Type.COLLECTION] = function (check, ele) {
  var collection = check.value;
  return collection.has(ele);
};
match[Type.FILTER] = function (check, ele) {
  var filter = check.value;
  return filter(ele);
};

// filter an existing collection
var filter = function filter(collection) {
  var self = this;

  // for 1 id #foo queries, just get the element
  if (self.length === 1 && self[0].checks.length === 1 && self[0].checks[0].type === Type.ID) {
    return collection.getElementById(self[0].checks[0].value).collection();
  }
  var selectorFunction = function selectorFunction(element) {
    for (var j = 0; j < self.length; j++) {
      var query = self[j];
      if (matches$1(query, element)) {
        return true;
      }
    }
    return false;
  };
  if (self.text() == null) {
    selectorFunction = function selectorFunction() {
      return true;
    };
  }
  return collection.filter(selectorFunction);
}; // filter

// does selector match a single element?
var matches = function matches(ele) {
  var self = this;
  for (var j = 0; j < self.length; j++) {
    var query = self[j];
    if (matches$1(query, ele)) {
      return true;
    }
  }
  return false;
}; // matches

var matching = {
  matches: matches,
  filter: filter
};

var Selector = function Selector(selector) {
  this.inputText = selector;
  this.currentSubject = null;
  this.compoundCount = 0;
  this.edgeCount = 0;
  this.length = 0;
  if (selector == null || string(selector) && selector.match(/^\s*$/)) ; else if (elementOrCollection(selector)) {
    this.addQuery({
      checks: [{
        type: Type.COLLECTION,
        value: selector.collection()
      }]
    });
  } else if (fn$6(selector)) {
    this.addQuery({
      checks: [{
        type: Type.FILTER,
        value: selector
      }]
    });
  } else if (string(selector)) {
    if (!this.parse(selector)) {
      this.invalid = true;
    }
  } else {
    error('A selector must be created from a string; found ');
  }
};
var selfn = Selector.prototype;
[parse$1, matching].forEach(function (p) {
  return extend(selfn, p);
});
selfn.text = function () {
  return this.inputText;
};
selfn.size = function () {
  return this.length;
};
selfn.eq = function (i) {
  return this[i];
};
selfn.sameText = function (otherSel) {
  return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();
};
selfn.addQuery = function (q) {
  this[this.length++] = q;
};
selfn.selector = selfn.toString;

var elesfn$g = {
  allAre: function allAre(selector) {
    var selObj = new Selector(selector);
    return this.every(function (ele) {
      return selObj.matches(ele);
    });
  },
  is: function is(selector) {
    var selObj = new Selector(selector);
    return this.some(function (ele) {
      return selObj.matches(ele);
    });
  },
  some: function some(fn, thisArg) {
    for (var i = 0; i < this.length; i++) {
      var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
      if (ret) {
        return true;
      }
    }
    return false;
  },
  every: function every(fn, thisArg) {
    for (var i = 0; i < this.length; i++) {
      var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
      if (!ret) {
        return false;
      }
    }
    return true;
  },
  same: function same(collection) {
    // cheap collection ref check
    if (this === collection) {
      return true;
    }
    collection = this.cy().collection(collection);
    var thisLength = this.length;
    var collectionLength = collection.length;

    // cheap length check
    if (thisLength !== collectionLength) {
      return false;
    }

    // cheap element ref check
    if (thisLength === 1) {
      return this[0] === collection[0];
    }
    return this.every(function (ele) {
      return collection.hasElementWithId(ele.id());
    });
  },
  anySame: function anySame(collection) {
    collection = this.cy().collection(collection);
    return this.some(function (ele) {
      return collection.hasElementWithId(ele.id());
    });
  },
  allAreNeighbors: function allAreNeighbors(collection) {
    collection = this.cy().collection(collection);
    var nhood = this.neighborhood();
    return collection.every(function (ele) {
      return nhood.hasElementWithId(ele.id());
    });
  },
  contains: function contains(collection) {
    collection = this.cy().collection(collection);
    var self = this;
    return collection.every(function (ele) {
      return self.hasElementWithId(ele.id());
    });
  }
};
elesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;
elesfn$g.has = elesfn$g.contains;
elesfn$g.equal = elesfn$g.equals = elesfn$g.same;

var cache = function cache(fn, name) {
  return function traversalCache(arg1, arg2, arg3, arg4) {
    var selectorOrEles = arg1;
    var eles = this;
    var key;
    if (selectorOrEles == null) {
      key = '';
    } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {
      key = selectorOrEles.id();
    }
    if (eles.length === 1 && key) {
      var _p = eles[0]._private;
      var tch = _p.traversalCache = _p.traversalCache || {};
      var ch = tch[name] = tch[name] || [];
      var hash = hashString(key);
      var cacheHit = ch[hash];
      if (cacheHit) {
        return cacheHit;
      } else {
        return ch[hash] = fn.call(eles, arg1, arg2, arg3, arg4);
      }
    } else {
      return fn.call(eles, arg1, arg2, arg3, arg4);
    }
  };
};

var elesfn$f = {
  parent: function parent(selector) {
    var parents = [];

    // optimisation for single ele call
    if (this.length === 1) {
      var parent = this[0]._private.parent;
      if (parent) {
        return parent;
      }
    }
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      var _parent = ele._private.parent;
      if (_parent) {
        parents.push(_parent);
      }
    }
    return this.spawn(parents, true).filter(selector);
  },
  parents: function parents(selector) {
    var parents = [];
    var eles = this.parent();
    while (eles.nonempty()) {
      for (var i = 0; i < eles.length; i++) {
        var ele = eles[i];
        parents.push(ele);
      }
      eles = eles.parent();
    }
    return this.spawn(parents, true).filter(selector);
  },
  commonAncestors: function commonAncestors(selector) {
    var ancestors;
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      var parents = ele.parents();
      ancestors = ancestors || parents;
      ancestors = ancestors.intersect(parents); // current list must be common with current ele parents set
    }
    return ancestors.filter(selector);
  },
  orphans: function orphans(selector) {
    return this.stdFilter(function (ele) {
      return ele.isOrphan();
    }).filter(selector);
  },
  nonorphans: function nonorphans(selector) {
    return this.stdFilter(function (ele) {
      return ele.isChild();
    }).filter(selector);
  },
  children: cache(function (selector) {
    var children = [];
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      var eleChildren = ele._private.children;
      for (var j = 0; j < eleChildren.length; j++) {
        children.push(eleChildren[j]);
      }
    }
    return this.spawn(children, true).filter(selector);
  }, 'children'),
  siblings: function siblings(selector) {
    return this.parent().children().not(this).filter(selector);
  },
  isParent: function isParent() {
    var ele = this[0];
    if (ele) {
      return ele.isNode() && ele._private.children.length !== 0;
    }
  },
  isChildless: function isChildless() {
    var ele = this[0];
    if (ele) {
      return ele.isNode() && ele._private.children.length === 0;
    }
  },
  isChild: function isChild() {
    var ele = this[0];
    if (ele) {
      return ele.isNode() && ele._private.parent != null;
    }
  },
  isOrphan: function isOrphan() {
    var ele = this[0];
    if (ele) {
      return ele.isNode() && ele._private.parent == null;
    }
  },
  descendants: function descendants(selector) {
    var elements = [];
    function add(eles) {
      for (var i = 0; i < eles.length; i++) {
        var ele = eles[i];
        elements.push(ele);
        if (ele.children().nonempty()) {
          add(ele.children());
        }
      }
    }
    add(this.children());
    return this.spawn(elements, true).filter(selector);
  }
};
function forEachCompound(eles, fn, includeSelf, recursiveStep) {
  var q = [];
  var did = new Set$1();
  var cy = eles.cy();
  var hasCompounds = cy.hasCompoundNodes();
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    if (includeSelf) {
      q.push(ele);
    } else if (hasCompounds) {
      recursiveStep(q, did, ele);
    }
  }
  while (q.length > 0) {
    var _ele = q.shift();
    fn(_ele);
    did.add(_ele.id());
    if (hasCompounds) {
      recursiveStep(q, did, _ele);
    }
  }
  return eles;
}
function addChildren(q, did, ele) {
  if (ele.isParent()) {
    var children = ele._private.children;
    for (var i = 0; i < children.length; i++) {
      var child = children[i];
      if (!did.has(child.id())) {
        q.push(child);
      }
    }
  }
}

// very efficient version of eles.add( eles.descendants() ).forEach()
// for internal use
elesfn$f.forEachDown = function (fn) {
  var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  return forEachCompound(this, fn, includeSelf, addChildren);
};
function addParent(q, did, ele) {
  if (ele.isChild()) {
    var parent = ele._private.parent;
    if (!did.has(parent.id())) {
      q.push(parent);
    }
  }
}
elesfn$f.forEachUp = function (fn) {
  var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  return forEachCompound(this, fn, includeSelf, addParent);
};
function addParentAndChildren(q, did, ele) {
  addParent(q, did, ele);
  addChildren(q, did, ele);
}
elesfn$f.forEachUpAndDown = function (fn) {
  var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  return forEachCompound(this, fn, includeSelf, addParentAndChildren);
};

// aliases
elesfn$f.ancestors = elesfn$f.parents;

var fn$5, elesfn$e;
fn$5 = elesfn$e = {
  data: define.data({
    field: 'data',
    bindingEvent: 'data',
    allowBinding: true,
    allowSetting: true,
    settingEvent: 'data',
    settingTriggersEvent: true,
    triggerFnName: 'trigger',
    allowGetting: true,
    immutableKeys: {
      'id': true,
      'source': true,
      'target': true,
      'parent': true
    },
    updateStyle: true
  }),
  removeData: define.removeData({
    field: 'data',
    event: 'data',
    triggerFnName: 'trigger',
    triggerEvent: true,
    immutableKeys: {
      'id': true,
      'source': true,
      'target': true,
      'parent': true
    },
    updateStyle: true
  }),
  scratch: define.data({
    field: 'scratch',
    bindingEvent: 'scratch',
    allowBinding: true,
    allowSetting: true,
    settingEvent: 'scratch',
    settingTriggersEvent: true,
    triggerFnName: 'trigger',
    allowGetting: true,
    updateStyle: true
  }),
  removeScratch: define.removeData({
    field: 'scratch',
    event: 'scratch',
    triggerFnName: 'trigger',
    triggerEvent: true,
    updateStyle: true
  }),
  rscratch: define.data({
    field: 'rscratch',
    allowBinding: false,
    allowSetting: true,
    settingTriggersEvent: false,
    allowGetting: true
  }),
  removeRscratch: define.removeData({
    field: 'rscratch',
    triggerEvent: false
  }),
  id: function id() {
    var ele = this[0];
    if (ele) {
      return ele._private.data.id;
    }
  }
};

// aliases
fn$5.attr = fn$5.data;
fn$5.removeAttr = fn$5.removeData;
var data = elesfn$e;

var elesfn$d = {};
function defineDegreeFunction(callback) {
  return function (includeLoops) {
    var self = this;
    if (includeLoops === undefined) {
      includeLoops = true;
    }
    if (self.length === 0) {
      return;
    }
    if (self.isNode() && !self.removed()) {
      var degree = 0;
      var node = self[0];
      var connectedEdges = node._private.edges;
      for (var i = 0; i < connectedEdges.length; i++) {
        var edge = connectedEdges[i];
        if (!includeLoops && edge.isLoop()) {
          continue;
        }
        degree += callback(node, edge);
      }
      return degree;
    } else {
      return;
    }
  };
}
extend(elesfn$d, {
  degree: defineDegreeFunction(function (node, edge) {
    if (edge.source().same(edge.target())) {
      return 2;
    } else {
      return 1;
    }
  }),
  indegree: defineDegreeFunction(function (node, edge) {
    if (edge.target().same(node)) {
      return 1;
    } else {
      return 0;
    }
  }),
  outdegree: defineDegreeFunction(function (node, edge) {
    if (edge.source().same(node)) {
      return 1;
    } else {
      return 0;
    }
  })
});
function defineDegreeBoundsFunction(degreeFn, callback) {
  return function (includeLoops) {
    var ret;
    var nodes = this.nodes();
    for (var i = 0; i < nodes.length; i++) {
      var ele = nodes[i];
      var degree = ele[degreeFn](includeLoops);
      if (degree !== undefined && (ret === undefined || callback(degree, ret))) {
        ret = degree;
      }
    }
    return ret;
  };
}
extend(elesfn$d, {
  minDegree: defineDegreeBoundsFunction('degree', function (degree, min) {
    return degree < min;
  }),
  maxDegree: defineDegreeBoundsFunction('degree', function (degree, max) {
    return degree > max;
  }),
  minIndegree: defineDegreeBoundsFunction('indegree', function (degree, min) {
    return degree < min;
  }),
  maxIndegree: defineDegreeBoundsFunction('indegree', function (degree, max) {
    return degree > max;
  }),
  minOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, min) {
    return degree < min;
  }),
  maxOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, max) {
    return degree > max;
  })
});
extend(elesfn$d, {
  totalDegree: function totalDegree(includeLoops) {
    var total = 0;
    var nodes = this.nodes();
    for (var i = 0; i < nodes.length; i++) {
      total += nodes[i].degree(includeLoops);
    }
    return total;
  }
});

var fn$4, elesfn$c;
var beforePositionSet = function beforePositionSet(eles, newPos, silent) {
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    if (!ele.locked()) {
      var oldPos = ele._private.position;
      var delta = {
        x: newPos.x != null ? newPos.x - oldPos.x : 0,
        y: newPos.y != null ? newPos.y - oldPos.y : 0
      };
      if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {
        ele.children().shift(delta, silent);
      }
      ele.dirtyBoundingBoxCache();
    }
  }
};
var positionDef = {
  field: 'position',
  bindingEvent: 'position',
  allowBinding: true,
  allowSetting: true,
  settingEvent: 'position',
  settingTriggersEvent: true,
  triggerFnName: 'emitAndNotify',
  allowGetting: true,
  validKeys: ['x', 'y'],
  beforeGet: function beforeGet(ele) {
    ele.updateCompoundBounds();
  },
  beforeSet: function beforeSet(eles, newPos) {
    beforePositionSet(eles, newPos, false);
  },
  onSet: function onSet(eles) {
    eles.dirtyCompoundBoundsCache();
  },
  canSet: function canSet(ele) {
    return !ele.locked();
  }
};
fn$4 = elesfn$c = {
  position: define.data(positionDef),
  // position but no notification to renderer
  silentPosition: define.data(extend({}, positionDef, {
    allowBinding: false,
    allowSetting: true,
    settingTriggersEvent: false,
    allowGetting: false,
    beforeSet: function beforeSet(eles, newPos) {
      beforePositionSet(eles, newPos, true);
    },
    onSet: function onSet(eles) {
      eles.dirtyCompoundBoundsCache();
    }
  })),
  positions: function positions(pos, silent) {
    if (plainObject(pos)) {
      if (silent) {
        this.silentPosition(pos);
      } else {
        this.position(pos);
      }
    } else if (fn$6(pos)) {
      var _fn = pos;
      var cy = this.cy();
      cy.startBatch();
      for (var i = 0; i < this.length; i++) {
        var ele = this[i];
        var _pos = undefined;
        if (_pos = _fn(ele, i)) {
          if (silent) {
            ele.silentPosition(_pos);
          } else {
            ele.position(_pos);
          }
        }
      }
      cy.endBatch();
    }
    return this; // chaining
  },
  silentPositions: function silentPositions(pos) {
    return this.positions(pos, true);
  },
  shift: function shift(dim, val, silent) {
    var delta;
    if (plainObject(dim)) {
      delta = {
        x: number$1(dim.x) ? dim.x : 0,
        y: number$1(dim.y) ? dim.y : 0
      };
      silent = val;
    } else if (string(dim) && number$1(val)) {
      delta = {
        x: 0,
        y: 0
      };
      delta[dim] = val;
    }
    if (delta != null) {
      var cy = this.cy();
      cy.startBatch();
      for (var i = 0; i < this.length; i++) {
        var ele = this[i];

        // exclude any node that is a descendant of the calling collection
        if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {
          continue;
        }
        var pos = ele.position();
        var newPos = {
          x: pos.x + delta.x,
          y: pos.y + delta.y
        };
        if (silent) {
          ele.silentPosition(newPos);
        } else {
          ele.position(newPos);
        }
      }
      cy.endBatch();
    }
    return this;
  },
  silentShift: function silentShift(dim, val) {
    if (plainObject(dim)) {
      this.shift(dim, true);
    } else if (string(dim) && number$1(val)) {
      this.shift(dim, val, true);
    }
    return this;
  },
  // get/set the rendered (i.e. on screen) positon of the element
  renderedPosition: function renderedPosition(dim, val) {
    var ele = this[0];
    var cy = this.cy();
    var zoom = cy.zoom();
    var pan = cy.pan();
    var rpos = plainObject(dim) ? dim : undefined;
    var setting = rpos !== undefined || val !== undefined && string(dim);
    if (ele && ele.isNode()) {
      // must have an element and must be a node to return position
      if (setting) {
        for (var i = 0; i < this.length; i++) {
          var _ele = this[i];
          if (val !== undefined) {
            // set one dimension
            _ele.position(dim, (val - pan[dim]) / zoom);
          } else if (rpos !== undefined) {
            // set whole position
            _ele.position(renderedToModelPosition(rpos, zoom, pan));
          }
        }
      } else {
        // getting
        var pos = ele.position();
        rpos = modelToRenderedPosition$1(pos, zoom, pan);
        if (dim === undefined) {
          // then return the whole rendered position
          return rpos;
        } else {
          // then return the specified dimension
          return rpos[dim];
        }
      }
    } else if (!setting) {
      return undefined; // for empty collection case
    }
    return this; // chaining
  },
  // get/set the position relative to the parent
  relativePosition: function relativePosition(dim, val) {
    var ele = this[0];
    var cy = this.cy();
    var ppos = plainObject(dim) ? dim : undefined;
    var setting = ppos !== undefined || val !== undefined && string(dim);
    var hasCompoundNodes = cy.hasCompoundNodes();
    if (ele && ele.isNode()) {
      // must have an element and must be a node to return position
      if (setting) {
        for (var i = 0; i < this.length; i++) {
          var _ele2 = this[i];
          var parent = hasCompoundNodes ? _ele2.parent() : null;
          var hasParent = parent && parent.length > 0;
          var relativeToParent = hasParent;
          if (hasParent) {
            parent = parent[0];
          }
          var origin = relativeToParent ? parent.position() : {
            x: 0,
            y: 0
          };
          if (val !== undefined) {
            // set one dimension
            _ele2.position(dim, val + origin[dim]);
          } else if (ppos !== undefined) {
            // set whole position
            _ele2.position({
              x: ppos.x + origin.x,
              y: ppos.y + origin.y
            });
          }
        }
      } else {
        // getting
        var pos = ele.position();
        var _parent = hasCompoundNodes ? ele.parent() : null;
        var _hasParent = _parent && _parent.length > 0;
        var _relativeToParent = _hasParent;
        if (_hasParent) {
          _parent = _parent[0];
        }
        var _origin = _relativeToParent ? _parent.position() : {
          x: 0,
          y: 0
        };
        ppos = {
          x: pos.x - _origin.x,
          y: pos.y - _origin.y
        };
        if (dim === undefined) {
          // then return the whole rendered position
          return ppos;
        } else {
          // then return the specified dimension
          return ppos[dim];
        }
      }
    } else if (!setting) {
      return undefined; // for empty collection case
    }
    return this; // chaining
  }
};

// aliases
fn$4.modelPosition = fn$4.point = fn$4.position;
fn$4.modelPositions = fn$4.points = fn$4.positions;
fn$4.renderedPoint = fn$4.renderedPosition;
fn$4.relativePoint = fn$4.relativePosition;
var position = elesfn$c;

var fn$3, elesfn$b;
fn$3 = elesfn$b = {};
elesfn$b.renderedBoundingBox = function (options) {
  var bb = this.boundingBox(options);
  var cy = this.cy();
  var zoom = cy.zoom();
  var pan = cy.pan();
  var x1 = bb.x1 * zoom + pan.x;
  var x2 = bb.x2 * zoom + pan.x;
  var y1 = bb.y1 * zoom + pan.y;
  var y2 = bb.y2 * zoom + pan.y;
  return {
    x1: x1,
    x2: x2,
    y1: y1,
    y2: y2,
    w: x2 - x1,
    h: y2 - y1
  };
};
elesfn$b.dirtyCompoundBoundsCache = function () {
  var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  var cy = this.cy();
  if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
    return this;
  }
  this.forEachUp(function (ele) {
    if (ele.isParent()) {
      var _p = ele._private;
      _p.compoundBoundsClean = false;
      _p.bbCache = null;
      if (!silent) {
        ele.emitAndNotify('bounds');
      }
    }
  });
  return this;
};
elesfn$b.updateCompoundBounds = function () {
  var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  var cy = this.cy();

  // not possible to do on non-compound graphs or with the style disabled
  if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
    return this;
  }

  // save cycles when batching -- but bounds will be stale (or not exist yet)
  if (!force && cy.batching()) {
    return this;
  }
  function update(parent) {
    if (!parent.isParent()) {
      return;
    }
    var _p = parent._private;
    var children = parent.children();
    var includeLabels = parent.pstyle('compound-sizing-wrt-labels').value === 'include';
    var min = {
      width: {
        val: parent.pstyle('min-width').pfValue,
        left: parent.pstyle('min-width-bias-left'),
        right: parent.pstyle('min-width-bias-right')
      },
      height: {
        val: parent.pstyle('min-height').pfValue,
        top: parent.pstyle('min-height-bias-top'),
        bottom: parent.pstyle('min-height-bias-bottom')
      }
    };
    var bb = children.boundingBox({
      includeLabels: includeLabels,
      includeOverlays: false,
      // updating the compound bounds happens outside of the regular
      // cache cycle (i.e. before fired events)
      useCache: false
    });
    var pos = _p.position;

    // if children take up zero area then keep position and fall back on stylesheet w/h
    if (bb.w === 0 || bb.h === 0) {
      bb = {
        w: parent.pstyle('width').pfValue,
        h: parent.pstyle('height').pfValue
      };
      bb.x1 = pos.x - bb.w / 2;
      bb.x2 = pos.x + bb.w / 2;
      bb.y1 = pos.y - bb.h / 2;
      bb.y2 = pos.y + bb.h / 2;
    }
    function computeBiasValues(propDiff, propBias, propBiasComplement) {
      var biasDiff = 0;
      var biasComplementDiff = 0;
      var biasTotal = propBias + propBiasComplement;
      if (propDiff > 0 && biasTotal > 0) {
        biasDiff = propBias / biasTotal * propDiff;
        biasComplementDiff = propBiasComplement / biasTotal * propDiff;
      }
      return {
        biasDiff: biasDiff,
        biasComplementDiff: biasComplementDiff
      };
    }
    function computePaddingValues(width, height, paddingObject, relativeTo) {
      // Assuming percentage is number from 0 to 1
      if (paddingObject.units === '%') {
        switch (relativeTo) {
          case 'width':
            return width > 0 ? paddingObject.pfValue * width : 0;
          case 'height':
            return height > 0 ? paddingObject.pfValue * height : 0;
          case 'average':
            return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;
          case 'min':
            return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;
          case 'max':
            return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;
          default:
            return 0;
        }
      } else if (paddingObject.units === 'px') {
        return paddingObject.pfValue;
      } else {
        return 0;
      }
    }
    var leftVal = min.width.left.value;
    if (min.width.left.units === 'px' && min.width.val > 0) {
      leftVal = leftVal * 100 / min.width.val;
    }
    var rightVal = min.width.right.value;
    if (min.width.right.units === 'px' && min.width.val > 0) {
      rightVal = rightVal * 100 / min.width.val;
    }
    var topVal = min.height.top.value;
    if (min.height.top.units === 'px' && min.height.val > 0) {
      topVal = topVal * 100 / min.height.val;
    }
    var bottomVal = min.height.bottom.value;
    if (min.height.bottom.units === 'px' && min.height.val > 0) {
      bottomVal = bottomVal * 100 / min.height.val;
    }
    var widthBiasDiffs = computeBiasValues(min.width.val - bb.w, leftVal, rightVal);
    var diffLeft = widthBiasDiffs.biasDiff;
    var diffRight = widthBiasDiffs.biasComplementDiff;
    var heightBiasDiffs = computeBiasValues(min.height.val - bb.h, topVal, bottomVal);
    var diffTop = heightBiasDiffs.biasDiff;
    var diffBottom = heightBiasDiffs.biasComplementDiff;
    _p.autoPadding = computePaddingValues(bb.w, bb.h, parent.pstyle('padding'), parent.pstyle('padding-relative-to').value);
    _p.autoWidth = Math.max(bb.w, min.width.val);
    pos.x = (-diffLeft + bb.x1 + bb.x2 + diffRight) / 2;
    _p.autoHeight = Math.max(bb.h, min.height.val);
    pos.y = (-diffTop + bb.y1 + bb.y2 + diffBottom) / 2;
  }
  for (var i = 0; i < this.length; i++) {
    var ele = this[i];
    var _p = ele._private;
    if (!_p.compoundBoundsClean || force) {
      update(ele);
      if (!cy.batching()) {
        _p.compoundBoundsClean = true;
      }
    }
  }
  return this;
};
var noninf = function noninf(x) {
  if (x === Infinity || x === -Infinity) {
    return 0;
  }
  return x;
};
var updateBounds = function updateBounds(b, x1, y1, x2, y2) {
  // don't update with zero area boxes
  if (x2 - x1 === 0 || y2 - y1 === 0) {
    return;
  }

  // don't update with null dim
  if (x1 == null || y1 == null || x2 == null || y2 == null) {
    return;
  }
  b.x1 = x1 < b.x1 ? x1 : b.x1;
  b.x2 = x2 > b.x2 ? x2 : b.x2;
  b.y1 = y1 < b.y1 ? y1 : b.y1;
  b.y2 = y2 > b.y2 ? y2 : b.y2;
  b.w = b.x2 - b.x1;
  b.h = b.y2 - b.y1;
};
var updateBoundsFromBox = function updateBoundsFromBox(b, b2) {
  if (b2 == null) {
    return b;
  }
  return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);
};
var prefixedProperty = function prefixedProperty(obj, field, prefix) {
  return getPrefixedProperty(obj, field, prefix);
};
var updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {
  if (ele.cy().headless()) {
    return;
  }
  var _p = ele._private;
  var rstyle = _p.rstyle;
  var halfArW = rstyle.arrowWidth / 2;
  var arrowType = ele.pstyle(prefix + '-arrow-shape').value;
  var x;
  var y;
  if (arrowType !== 'none') {
    if (prefix === 'source') {
      x = rstyle.srcX;
      y = rstyle.srcY;
    } else if (prefix === 'target') {
      x = rstyle.tgtX;
      y = rstyle.tgtY;
    } else {
      x = rstyle.midX;
      y = rstyle.midY;
    }

    // always store the individual arrow bounds
    var bbs = _p.arrowBounds = _p.arrowBounds || {};
    var bb = bbs[prefix] = bbs[prefix] || {};
    bb.x1 = x - halfArW;
    bb.y1 = y - halfArW;
    bb.x2 = x + halfArW;
    bb.y2 = y + halfArW;
    bb.w = bb.x2 - bb.x1;
    bb.h = bb.y2 - bb.y1;
    expandBoundingBox(bb, 1);
    updateBounds(bounds, bb.x1, bb.y1, bb.x2, bb.y2);
  }
};
var updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {
  if (ele.cy().headless()) {
    return;
  }
  var prefixDash;
  if (prefix) {
    prefixDash = prefix + '-';
  } else {
    prefixDash = '';
  }
  var _p = ele._private;
  var rstyle = _p.rstyle;
  var label = ele.pstyle(prefixDash + 'label').strValue;
  if (label) {
    var halign = ele.pstyle('text-halign');
    var valign = ele.pstyle('text-valign');
    var labelWidth = prefixedProperty(rstyle, 'labelWidth', prefix);
    var labelHeight = prefixedProperty(rstyle, 'labelHeight', prefix);
    var labelX = prefixedProperty(rstyle, 'labelX', prefix);
    var labelY = prefixedProperty(rstyle, 'labelY', prefix);
    var marginX = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
    var marginY = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
    var isEdge = ele.isEdge();
    var rotation = ele.pstyle(prefixDash + 'text-rotation');
    var outlineWidth = ele.pstyle('text-outline-width').pfValue;
    var borderWidth = ele.pstyle('text-border-width').pfValue;
    var halfBorderWidth = borderWidth / 2;
    var padding = ele.pstyle('text-background-padding').pfValue;
    var marginOfError = 2; // expand to work around browser dimension inaccuracies

    var lh = labelHeight;
    var lw = labelWidth;
    var lw_2 = lw / 2;
    var lh_2 = lh / 2;
    var lx1, lx2, ly1, ly2;
    if (isEdge) {
      lx1 = labelX - lw_2;
      lx2 = labelX + lw_2;
      ly1 = labelY - lh_2;
      ly2 = labelY + lh_2;
    } else {
      switch (halign.value) {
        case 'left':
          lx1 = labelX - lw;
          lx2 = labelX;
          break;
        case 'center':
          lx1 = labelX - lw_2;
          lx2 = labelX + lw_2;
          break;
        case 'right':
          lx1 = labelX;
          lx2 = labelX + lw;
          break;
      }
      switch (valign.value) {
        case 'top':
          ly1 = labelY - lh;
          ly2 = labelY;
          break;
        case 'center':
          ly1 = labelY - lh_2;
          ly2 = labelY + lh_2;
          break;
        case 'bottom':
          ly1 = labelY;
          ly2 = labelY + lh;
          break;
      }
    }

    // shift by margin and expand by outline and border
    var leftPad = marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
    var rightPad = marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
    var topPad = marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
    var botPad = marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
    lx1 += leftPad;
    lx2 += rightPad;
    ly1 += topPad;
    ly2 += botPad;

    // always store the unrotated label bounds separately
    var bbPrefix = prefix || 'main';
    var bbs = _p.labelBounds;
    var bb = bbs[bbPrefix] = bbs[bbPrefix] || {};
    bb.x1 = lx1;
    bb.y1 = ly1;
    bb.x2 = lx2;
    bb.y2 = ly2;
    bb.w = lx2 - lx1;
    bb.h = ly2 - ly1;
    bb.leftPad = leftPad;
    bb.rightPad = rightPad;
    bb.topPad = topPad;
    bb.botPad = botPad;
    var isAutorotate = isEdge && rotation.strValue === 'autorotate';
    var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;
    if (isAutorotate || isPfValue) {
      var theta = isAutorotate ? prefixedProperty(_p.rstyle, 'labelAngle', prefix) : rotation.pfValue;
      var cos = Math.cos(theta);
      var sin = Math.sin(theta);

      // rotation point (default value for center-center)
      var xo = (lx1 + lx2) / 2;
      var yo = (ly1 + ly2) / 2;
      if (!isEdge) {
        switch (halign.value) {
          case 'left':
            xo = lx2;
            break;
          case 'right':
            xo = lx1;
            break;
        }
        switch (valign.value) {
          case 'top':
            yo = ly2;
            break;
          case 'bottom':
            yo = ly1;
            break;
        }
      }
      var rotate = function rotate(x, y) {
        x = x - xo;
        y = y - yo;
        return {
          x: x * cos - y * sin + xo,
          y: x * sin + y * cos + yo
        };
      };
      var px1y1 = rotate(lx1, ly1);
      var px1y2 = rotate(lx1, ly2);
      var px2y1 = rotate(lx2, ly1);
      var px2y2 = rotate(lx2, ly2);
      lx1 = Math.min(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
      lx2 = Math.max(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
      ly1 = Math.min(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
      ly2 = Math.max(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
    }
    var bbPrefixRot = bbPrefix + 'Rot';
    var bbRot = bbs[bbPrefixRot] = bbs[bbPrefixRot] || {};
    bbRot.x1 = lx1;
    bbRot.y1 = ly1;
    bbRot.x2 = lx2;
    bbRot.y2 = ly2;
    bbRot.w = lx2 - lx1;
    bbRot.h = ly2 - ly1;
    updateBounds(bounds, lx1, ly1, lx2, ly2);
    updateBounds(_p.labelBounds.all, lx1, ly1, lx2, ly2);
  }
  return bounds;
};
var updateBoundsFromOutline = function updateBoundsFromOutline(bounds, ele) {
  if (ele.cy().headless()) {
    return;
  }
  var outlineOpacity = ele.pstyle('outline-opacity').value;
  var outlineWidth = ele.pstyle('outline-width').value;
  var outlineOffset = ele.pstyle('outline-offset').value;
  var expansion = outlineWidth + outlineOffset;
  updateBoundsFromMiter(bounds, ele, outlineOpacity, expansion, 'outside', expansion / 2);
};
var updateBoundsFromMiter = function updateBoundsFromMiter(bounds, ele, opacity, expansionSize, expansionPosition, useFallbackValue) {
  if (opacity === 0 || expansionSize <= 0 || expansionPosition === 'inside') {
    return;
  }
  var cy = ele.cy();
  var shape = ele.pstyle('shape').value;
  var rshape = cy.renderer().nodeShapes[shape];
  var _ele$position = ele.position(),
    x = _ele$position.x,
    y = _ele$position.y;
  var w = ele.width();
  var h = ele.height();
  if (rshape.hasMiterBounds) {
    if (expansionPosition === 'center') {
      expansionSize /= 2;
    }
    var mbb = rshape.miterBounds(x, y, w, h, expansionSize);
    updateBoundsFromBox(bounds, mbb);
  } else if (useFallbackValue != null && useFallbackValue > 0) {
    expandBoundingBoxSides(bounds, [useFallbackValue, useFallbackValue, useFallbackValue, useFallbackValue]);
  }
};
var updateBoundsFromMiterBorder = function updateBoundsFromMiterBorder(bounds, ele) {
  if (ele.cy().headless()) {
    return;
  }
  var borderOpacity = ele.pstyle('border-opacity').value;
  var borderWidth = ele.pstyle('border-width').pfValue;
  var borderPosition = ele.pstyle('border-position').value;
  updateBoundsFromMiter(bounds, ele, borderOpacity, borderWidth, borderPosition);
};

// get the bounding box of the elements (in raw model position)
var boundingBoxImpl = function boundingBoxImpl(ele, options) {
  var cy = ele._private.cy;
  var styleEnabled = cy.styleEnabled();
  var headless = cy.headless();
  var bounds = makeBoundingBox();
  var _p = ele._private;
  var isNode = ele.isNode();
  var isEdge = ele.isEdge();
  var ex1, ex2, ey1, ey2; // extrema of body / lines
  var x, y; // node pos
  var rstyle = _p.rstyle;
  var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0];

  // must use `display` prop only, as reading `compound.width()` causes recursion
  // (other factors like width values will be considered later in this function anyway)
  var isDisplayed = function isDisplayed(ele) {
    return ele.pstyle('display').value !== 'none';
  };
  var displayed = !styleEnabled || isDisplayed(ele)

  // must take into account connected nodes b/c of implicit edge hiding on display:none node
  && (!isEdge || isDisplayed(ele.source()) && isDisplayed(ele.target()));
  if (displayed) {
    // displayed suffices, since we will find zero area eles anyway
    var overlayOpacity = 0;
    var overlayPadding = 0;
    if (styleEnabled && options.includeOverlays) {
      overlayOpacity = ele.pstyle('overlay-opacity').value;
      if (overlayOpacity !== 0) {
        overlayPadding = ele.pstyle('overlay-padding').value;
      }
    }
    var underlayOpacity = 0;
    var underlayPadding = 0;
    if (styleEnabled && options.includeUnderlays) {
      underlayOpacity = ele.pstyle('underlay-opacity').value;
      if (underlayOpacity !== 0) {
        underlayPadding = ele.pstyle('underlay-padding').value;
      }
    }
    var padding = Math.max(overlayPadding, underlayPadding);
    var w = 0;
    var wHalf = 0;
    if (styleEnabled) {
      w = ele.pstyle('width').pfValue;
      wHalf = w / 2;
    }
    if (isNode && options.includeNodes) {
      var pos = ele.position();
      x = pos.x;
      y = pos.y;
      var _w = ele.outerWidth();
      var halfW = _w / 2;
      var h = ele.outerHeight();
      var halfH = h / 2;

      // handle node dimensions
      /////////////////////////

      ex1 = x - halfW;
      ex2 = x + halfW;
      ey1 = y - halfH;
      ey2 = y + halfH;
      updateBounds(bounds, ex1, ey1, ex2, ey2);
      if (styleEnabled) {
        updateBoundsFromOutline(bounds, ele);
      }
      if (styleEnabled && options.includeOutlines && !headless) {
        updateBoundsFromOutline(bounds, ele);
      }
      if (styleEnabled) {
        updateBoundsFromMiterBorder(bounds, ele);
      }
    } else if (isEdge && options.includeEdges) {
      if (styleEnabled && !headless) {
        var curveStyle = ele.pstyle('curve-style').strValue;

        // handle edge dimensions (rough box estimate)
        //////////////////////////////////////////////

        ex1 = Math.min(rstyle.srcX, rstyle.midX, rstyle.tgtX);
        ex2 = Math.max(rstyle.srcX, rstyle.midX, rstyle.tgtX);
        ey1 = Math.min(rstyle.srcY, rstyle.midY, rstyle.tgtY);
        ey2 = Math.max(rstyle.srcY, rstyle.midY, rstyle.tgtY);

        // take into account edge width
        ex1 -= wHalf;
        ex2 += wHalf;
        ey1 -= wHalf;
        ey2 += wHalf;
        updateBounds(bounds, ex1, ey1, ex2, ey2);

        // precise edges
        ////////////////

        if (curveStyle === 'haystack') {
          var hpts = rstyle.haystackPts;
          if (hpts && hpts.length === 2) {
            ex1 = hpts[0].x;
            ey1 = hpts[0].y;
            ex2 = hpts[1].x;
            ey2 = hpts[1].y;
            if (ex1 > ex2) {
              var temp = ex1;
              ex1 = ex2;
              ex2 = temp;
            }
            if (ey1 > ey2) {
              var _temp = ey1;
              ey1 = ey2;
              ey2 = _temp;
            }
            updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);
          }
        } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || endsWith(curveStyle, 'taxi')) {
          var pts;
          switch (curveStyle) {
            case 'bezier':
            case 'unbundled-bezier':
              pts = rstyle.bezierPts;
              break;
            case 'segments':
            case 'taxi':
            case 'round-segments':
            case 'round-taxi':
              pts = rstyle.linePts;
              break;
          }
          if (pts != null) {
            for (var j = 0; j < pts.length; j++) {
              var pt = pts[j];
              ex1 = pt.x - wHalf;
              ex2 = pt.x + wHalf;
              ey1 = pt.y - wHalf;
              ey2 = pt.y + wHalf;
              updateBounds(bounds, ex1, ey1, ex2, ey2);
            }
          }
        } // bezier-like or segment-like edge
      } else {
        // headless or style disabled

        // fallback on source and target positions
        //////////////////////////////////////////

        var n1 = ele.source();
        var n1pos = n1.position();
        var n2 = ele.target();
        var n2pos = n2.position();
        ex1 = n1pos.x;
        ex2 = n2pos.x;
        ey1 = n1pos.y;
        ey2 = n2pos.y;
        if (ex1 > ex2) {
          var _temp2 = ex1;
          ex1 = ex2;
          ex2 = _temp2;
        }
        if (ey1 > ey2) {
          var _temp3 = ey1;
          ey1 = ey2;
          ey2 = _temp3;
        }

        // take into account edge width
        ex1 -= wHalf;
        ex2 += wHalf;
        ey1 -= wHalf;
        ey2 += wHalf;
        updateBounds(bounds, ex1, ey1, ex2, ey2);
      } // headless or style disabled
    } // edges

    // handle edge arrow size
    /////////////////////////

    if (styleEnabled && options.includeEdges && isEdge) {
      updateBoundsFromArrow(bounds, ele, 'mid-source');
      updateBoundsFromArrow(bounds, ele, 'mid-target');
      updateBoundsFromArrow(bounds, ele, 'source');
      updateBoundsFromArrow(bounds, ele, 'target');
    }

    // ghost
    ////////

    if (styleEnabled) {
      var ghost = ele.pstyle('ghost').value === 'yes';
      if (ghost) {
        var gx = ele.pstyle('ghost-offset-x').pfValue;
        var gy = ele.pstyle('ghost-offset-y').pfValue;
        updateBounds(bounds, bounds.x1 + gx, bounds.y1 + gy, bounds.x2 + gx, bounds.y2 + gy);
      }
    }

    // always store the body bounds separately from the labels
    var bbBody = _p.bodyBounds = _p.bodyBounds || {};
    assignBoundingBox(bbBody, bounds);
    expandBoundingBoxSides(bbBody, manualExpansion);
    expandBoundingBox(bbBody, 1); // expand to work around browser dimension inaccuracies

    // overlay
    //////////

    if (styleEnabled) {
      ex1 = bounds.x1;
      ex2 = bounds.x2;
      ey1 = bounds.y1;
      ey2 = bounds.y2;
      updateBounds(bounds, ex1 - padding, ey1 - padding, ex2 + padding, ey2 + padding);
    }

    // always store the body bounds separately from the labels
    var bbOverlay = _p.overlayBounds = _p.overlayBounds || {};
    assignBoundingBox(bbOverlay, bounds);
    expandBoundingBoxSides(bbOverlay, manualExpansion);
    expandBoundingBox(bbOverlay, 1); // expand to work around browser dimension inaccuracies

    // handle label dimensions
    //////////////////////////

    var bbLabels = _p.labelBounds = _p.labelBounds || {};
    if (bbLabels.all != null) {
      clearBoundingBox(bbLabels.all);
    } else {
      bbLabels.all = makeBoundingBox();
    }
    if (styleEnabled && options.includeLabels) {
      if (options.includeMainLabels) {
        updateBoundsFromLabel(bounds, ele, null);
      }
      if (isEdge) {
        if (options.includeSourceLabels) {
          updateBoundsFromLabel(bounds, ele, 'source');
        }
        if (options.includeTargetLabels) {
          updateBoundsFromLabel(bounds, ele, 'target');
        }
      }
    } // style enabled for labels
  } // if displayed

  bounds.x1 = noninf(bounds.x1);
  bounds.y1 = noninf(bounds.y1);
  bounds.x2 = noninf(bounds.x2);
  bounds.y2 = noninf(bounds.y2);
  bounds.w = noninf(bounds.x2 - bounds.x1);
  bounds.h = noninf(bounds.y2 - bounds.y1);
  if (bounds.w > 0 && bounds.h > 0 && displayed) {
    expandBoundingBoxSides(bounds, manualExpansion);

    // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides
    expandBoundingBox(bounds, 1);
  }
  return bounds;
};
var getKey = function getKey(opts) {
  var i = 0;
  var tf = function tf(val) {
    return (val ? 1 : 0) << i++;
  };
  var key = 0;
  key += tf(opts.incudeNodes);
  key += tf(opts.includeEdges);
  key += tf(opts.includeLabels);
  key += tf(opts.includeMainLabels);
  key += tf(opts.includeSourceLabels);
  key += tf(opts.includeTargetLabels);
  key += tf(opts.includeOverlays);
  key += tf(opts.includeOutlines);
  return key;
};
var getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {
  var r = function r(x) {
    return Math.round(x);
  };
  if (ele.isEdge()) {
    var p1 = ele.source().position();
    var p2 = ele.target().position();
    return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);
  } else {
    var p = ele.position();
    return hashIntsArray([r(p.x), r(p.y)]);
  }
};
var cachedBoundingBoxImpl = function cachedBoundingBoxImpl(ele, opts) {
  var _p = ele._private;
  var bb;
  var isEdge = ele.isEdge();
  var key = opts == null ? defBbOptsKey : getKey(opts);
  var usingDefOpts = key === defBbOptsKey;
  if (_p.bbCache == null) {
    bb = boundingBoxImpl(ele, defBbOpts);
    _p.bbCache = bb;
    _p.bbCachePosKey = getBoundingBoxPosKey(ele);
  } else {
    bb = _p.bbCache;
  }

  // not using def opts => need to build up bb from combination of sub bbs
  if (!usingDefOpts) {
    var isNode = ele.isNode();
    bb = makeBoundingBox();
    if (opts.includeNodes && isNode || opts.includeEdges && !isNode) {
      if (opts.includeOverlays) {
        updateBoundsFromBox(bb, _p.overlayBounds);
      } else {
        updateBoundsFromBox(bb, _p.bodyBounds);
      }
    }
    if (opts.includeLabels) {
      if (opts.includeMainLabels && (!isEdge || opts.includeSourceLabels && opts.includeTargetLabels)) {
        updateBoundsFromBox(bb, _p.labelBounds.all);
      } else {
        if (opts.includeMainLabels) {
          updateBoundsFromBox(bb, _p.labelBounds.mainRot);
        }
        if (opts.includeSourceLabels) {
          updateBoundsFromBox(bb, _p.labelBounds.sourceRot);
        }
        if (opts.includeTargetLabels) {
          updateBoundsFromBox(bb, _p.labelBounds.targetRot);
        }
      }
    }
    bb.w = bb.x2 - bb.x1;
    bb.h = bb.y2 - bb.y1;
  }
  return bb;
};
var defBbOpts = {
  includeNodes: true,
  includeEdges: true,
  includeLabels: true,
  includeMainLabels: true,
  includeSourceLabels: true,
  includeTargetLabels: true,
  includeOverlays: true,
  includeUnderlays: true,
  includeOutlines: true,
  useCache: true
};
var defBbOptsKey = getKey(defBbOpts);
var filledBbOpts = defaults$g(defBbOpts);
elesfn$b.boundingBox = function (options) {
  var bounds;
  var useCache = options === undefined || options.useCache === undefined || options.useCache === true;
  var isDirty = memoize(function (ele) {
    var _p = ele._private;
    return _p.bbCache == null || _p.styleDirty || _p.bbCachePosKey !== getBoundingBoxPosKey(ele);
  }, function (ele) {
    return ele.id();
  });

  // the main usecase is ele.boundingBox() for a single element with no/def options
  // specified s.t. the cache is used, so check for this case to make it faster by
  // avoiding the overhead of the rest of the function
  if (useCache && this.length === 1 && !isDirty(this[0])) {
    if (options === undefined) {
      options = defBbOpts;
    } else {
      options = filledBbOpts(options);
    }
    bounds = cachedBoundingBoxImpl(this[0], options);
  } else {
    bounds = makeBoundingBox();
    options = options || defBbOpts;
    var opts = filledBbOpts(options);
    var eles = this;
    var cy = eles.cy();
    var styleEnabled = cy.styleEnabled();

    // cache the isDirty state for all eles, edges first since they depend on node state
    this.edges().forEach(isDirty);
    this.nodes().forEach(isDirty);
    if (styleEnabled) {
      this.recalculateRenderedStyle(useCache);
    }
    this.updateCompoundBounds(!useCache);
    for (var i = 0; i < eles.length; i++) {
      var ele = eles[i];
      if (isDirty(ele)) {
        ele.dirtyBoundingBoxCache();
      }
      updateBoundsFromBox(bounds, cachedBoundingBoxImpl(ele, opts));
    }
  }
  bounds.x1 = noninf(bounds.x1);
  bounds.y1 = noninf(bounds.y1);
  bounds.x2 = noninf(bounds.x2);
  bounds.y2 = noninf(bounds.y2);
  bounds.w = noninf(bounds.x2 - bounds.x1);
  bounds.h = noninf(bounds.y2 - bounds.y1);
  return bounds;
};
elesfn$b.dirtyBoundingBoxCache = function () {
  for (var i = 0; i < this.length; i++) {
    var _p = this[i]._private;
    _p.bbCache = null;
    _p.bbCachePosKey = null;
    _p.bodyBounds = null;
    _p.overlayBounds = null;
    _p.labelBounds.all = null;
    _p.labelBounds.source = null;
    _p.labelBounds.target = null;
    _p.labelBounds.main = null;
    _p.labelBounds.sourceRot = null;
    _p.labelBounds.targetRot = null;
    _p.labelBounds.mainRot = null;
    _p.arrowBounds.source = null;
    _p.arrowBounds.target = null;
    _p.arrowBounds['mid-source'] = null;
    _p.arrowBounds['mid-target'] = null;
  }
  this.emitAndNotify('bounds');
  return this;
};

// private helper to get bounding box for custom node positions
// - good for perf in certain cases but currently requires dirtying the rendered style
// - would be better to not modify the nodes but the nodes are read directly everywhere in the renderer...
// - try to use for only things like discrete layouts where the node position would change anyway
elesfn$b.boundingBoxAt = function (fn) {
  var nodes = this.nodes();
  var cy = this.cy();
  var hasCompoundNodes = cy.hasCompoundNodes();
  var parents = cy.collection();
  if (hasCompoundNodes) {
    parents = nodes.filter(function (node) {
      return node.isParent();
    });
    nodes = nodes.not(parents);
  }
  if (plainObject(fn)) {
    var obj = fn;
    fn = function fn() {
      return obj;
    };
  }
  var storeOldPos = function storeOldPos(node, i) {
    return node._private.bbAtOldPos = fn(node, i);
  };
  var getOldPos = function getOldPos(node) {
    return node._private.bbAtOldPos;
  };
  cy.startBatch();
  nodes.forEach(storeOldPos).silentPositions(fn);
  if (hasCompoundNodes) {
    parents.dirtyCompoundBoundsCache();
    parents.dirtyBoundingBoxCache();
    parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  }
  var bb = copyBoundingBox(this.boundingBox({
    useCache: false
  }));
  nodes.silentPositions(getOldPos);
  if (hasCompoundNodes) {
    parents.dirtyCompoundBoundsCache();
    parents.dirtyBoundingBoxCache();
    parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  }
  cy.endBatch();
  return bb;
};
fn$3.boundingbox = fn$3.bb = fn$3.boundingBox;
fn$3.renderedBoundingbox = fn$3.renderedBoundingBox;
var bounds = elesfn$b;

var fn$2, elesfn$a;
fn$2 = elesfn$a = {};
var defineDimFns = function defineDimFns(opts) {
  opts.uppercaseName = capitalize(opts.name);
  opts.autoName = 'auto' + opts.uppercaseName;
  opts.labelName = 'label' + opts.uppercaseName;
  opts.outerName = 'outer' + opts.uppercaseName;
  opts.uppercaseOuterName = capitalize(opts.outerName);
  fn$2[opts.name] = function dimImpl() {
    var ele = this[0];
    var _p = ele._private;
    var cy = _p.cy;
    var styleEnabled = cy._private.styleEnabled;
    if (ele) {
      if (styleEnabled) {
        if (ele.isParent()) {
          ele.updateCompoundBounds();
          return _p[opts.autoName] || 0;
        }
        var d = ele.pstyle(opts.name);
        switch (d.strValue) {
          case 'label':
            ele.recalculateRenderedStyle();
            return _p.rstyle[opts.labelName] || 0;
          default:
            return d.pfValue;
        }
      } else {
        return 1;
      }
    }
  };
  fn$2['outer' + opts.uppercaseName] = function outerDimImpl() {
    var ele = this[0];
    var _p = ele._private;
    var cy = _p.cy;
    var styleEnabled = cy._private.styleEnabled;
    if (ele) {
      if (styleEnabled) {
        var dim = ele[opts.name]();
        var borderPos = ele.pstyle('border-position').value;
        var border;
        if (borderPos === 'center') {
          border = ele.pstyle('border-width').pfValue; // n.b. 1/2 each side
        } else if (borderPos === 'outside') {
          border = 2 * ele.pstyle('border-width').pfValue;
        } else {
          // 'inside'
          border = 0;
        }
        var padding = 2 * ele.padding();
        return dim + border + padding;
      } else {
        return 1;
      }
    }
  };
  fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {
    var ele = this[0];
    if (ele) {
      var d = ele[opts.name]();
      return d * this.cy().zoom();
    }
  };
  fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {
    var ele = this[0];
    if (ele) {
      var od = ele[opts.outerName]();
      return od * this.cy().zoom();
    }
  };
};
defineDimFns({
  name: 'width'
});
defineDimFns({
  name: 'height'
});
elesfn$a.padding = function () {
  var ele = this[0];
  var _p = ele._private;
  if (ele.isParent()) {
    ele.updateCompoundBounds();
    if (_p.autoPadding !== undefined) {
      return _p.autoPadding;
    } else {
      return ele.pstyle('padding').pfValue;
    }
  } else {
    return ele.pstyle('padding').pfValue;
  }
};
elesfn$a.paddedHeight = function () {
  var ele = this[0];
  return ele.height() + 2 * ele.padding();
};
elesfn$a.paddedWidth = function () {
  var ele = this[0];
  return ele.width() + 2 * ele.padding();
};
var widthHeight = elesfn$a;

var ifEdge = function ifEdge(ele, getValue) {
  if (ele.isEdge() && ele.takesUpSpace()) {
    return getValue(ele);
  }
};
var ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {
  if (ele.isEdge() && ele.takesUpSpace()) {
    var cy = ele.cy();
    return modelToRenderedPosition$1(getPoint(ele), cy.zoom(), cy.pan());
  }
};
var ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {
  if (ele.isEdge() && ele.takesUpSpace()) {
    var cy = ele.cy();
    var pan = cy.pan();
    var zoom = cy.zoom();
    return getPoints(ele).map(function (p) {
      return modelToRenderedPosition$1(p, zoom, pan);
    });
  }
};
var controlPoints = function controlPoints(ele) {
  return ele.renderer().getControlPoints(ele);
};
var segmentPoints = function segmentPoints(ele) {
  return ele.renderer().getSegmentPoints(ele);
};
var sourceEndpoint = function sourceEndpoint(ele) {
  return ele.renderer().getSourceEndpoint(ele);
};
var targetEndpoint = function targetEndpoint(ele) {
  return ele.renderer().getTargetEndpoint(ele);
};
var midpoint = function midpoint(ele) {
  return ele.renderer().getEdgeMidpoint(ele);
};
var pts = {
  controlPoints: {
    get: controlPoints,
    mult: true
  },
  segmentPoints: {
    get: segmentPoints,
    mult: true
  },
  sourceEndpoint: {
    get: sourceEndpoint
  },
  targetEndpoint: {
    get: targetEndpoint
  },
  midpoint: {
    get: midpoint
  }
};
var renderedName = function renderedName(name) {
  return 'rendered' + name[0].toUpperCase() + name.substr(1);
};
var edgePoints = Object.keys(pts).reduce(function (obj, name) {
  var spec = pts[name];
  var rName = renderedName(name);
  obj[name] = function () {
    return ifEdge(this, spec.get);
  };
  if (spec.mult) {
    obj[rName] = function () {
      return ifEdgeRenderedPositions(this, spec.get);
    };
  } else {
    obj[rName] = function () {
      return ifEdgeRenderedPosition(this, spec.get);
    };
  }
  return obj;
}, {});

var dimensions = extend({}, position, bounds, widthHeight, edgePoints);

/*!
Event object based on jQuery events, MIT license

https://jquery.org/license/
https://tldrlegal.com/license/mit-license
https://github.com/jquery/jquery/blob/master/src/event.js
*/

var Event = function Event(src, props) {
  this.recycle(src, props);
};
function returnFalse() {
  return false;
}
function returnTrue() {
  return true;
}

// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
Event.prototype = {
  instanceString: function instanceString() {
    return 'event';
  },
  recycle: function recycle(src, props) {
    this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;
    if (src != null && src.preventDefault) {
      // Browser Event object
      this.type = src.type;

      // Events bubbling up the document may have been marked as prevented
      // by a handler lower down the tree; reflect the correct value.
      this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse;
    } else if (src != null && src.type) {
      // Plain object containing all event details
      props = src;
    } else {
      // Event string
      this.type = src;
    }

    // Put explicitly provided properties onto the event object
    if (props != null) {
      // more efficient to manually copy fields we use
      this.originalEvent = props.originalEvent;
      this.type = props.type != null ? props.type : this.type;
      this.cy = props.cy;
      this.target = props.target;
      this.position = props.position;
      this.renderedPosition = props.renderedPosition;
      this.namespace = props.namespace;
      this.layout = props.layout;
    }
    if (this.cy != null && this.position != null && this.renderedPosition == null) {
      // create a rendered position based on the passed position
      var pos = this.position;
      var zoom = this.cy.zoom();
      var pan = this.cy.pan();
      this.renderedPosition = {
        x: pos.x * zoom + pan.x,
        y: pos.y * zoom + pan.y
      };
    }

    // Create a timestamp if incoming event doesn't have one
    this.timeStamp = src && src.timeStamp || Date.now();
  },
  preventDefault: function preventDefault() {
    this.isDefaultPrevented = returnTrue;
    var e = this.originalEvent;
    if (!e) {
      return;
    }

    // if preventDefault exists run it on the original event
    if (e.preventDefault) {
      e.preventDefault();
    }
  },
  stopPropagation: function stopPropagation() {
    this.isPropagationStopped = returnTrue;
    var e = this.originalEvent;
    if (!e) {
      return;
    }

    // if stopPropagation exists run it on the original event
    if (e.stopPropagation) {
      e.stopPropagation();
    }
  },
  stopImmediatePropagation: function stopImmediatePropagation() {
    this.isImmediatePropagationStopped = returnTrue;
    this.stopPropagation();
  },
  isDefaultPrevented: returnFalse,
  isPropagationStopped: returnFalse,
  isImmediatePropagationStopped: returnFalse
};

var eventRegex = /^([^.]+)(\.(?:[^.]+))?$/; // regex for matching event strings (e.g. "click.namespace")
var universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally

var defaults$8 = {
  qualifierCompare: function qualifierCompare(q1, q2) {
    return q1 === q2;
  },
  eventMatches: function eventMatches(/*context, listener, eventObj*/
  ) {
    return true;
  },
  addEventFields: function addEventFields(/*context, evt*/
  ) {},
  callbackContext: function callbackContext(context /*, listener, eventObj*/) {
    return context;
  },
  beforeEmit: function beforeEmit(/* context, listener, eventObj */
  ) {},
  afterEmit: function afterEmit(/* context, listener, eventObj */
  ) {},
  bubble: function bubble(/*context*/
  ) {
    return false;
  },
  parent: function parent(/*context*/
  ) {
    return null;
  },
  context: null
};
var defaultsKeys = Object.keys(defaults$8);
var emptyOpts = {};
function Emitter() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;
  var context = arguments.length > 1 ? arguments[1] : undefined;
  // micro-optimisation vs Object.assign() -- reduces Element instantiation time
  for (var i = 0; i < defaultsKeys.length; i++) {
    var key = defaultsKeys[i];
    this[key] = opts[key] || defaults$8[key];
  }
  this.context = context || this.context;
  this.listeners = [];
  this.emitting = 0;
}
var p = Emitter.prototype;
var forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {
  if (fn$6(qualifier)) {
    callback = qualifier;
    qualifier = null;
  }
  if (confOverrides) {
    if (conf == null) {
      conf = confOverrides;
    } else {
      conf = extend({}, conf, confOverrides);
    }
  }
  var eventList = array(events) ? events : events.split(/\s+/);
  for (var i = 0; i < eventList.length; i++) {
    var evt = eventList[i];
    if (emptyString(evt)) {
      continue;
    }
    var match = evt.match(eventRegex); // type[.namespace]

    if (match) {
      var type = match[1];
      var namespace = match[2] ? match[2] : null;
      var ret = handler(self, evt, type, namespace, qualifier, callback, conf);
      if (ret === false) {
        break;
      } // allow exiting early
    }
  }
};
var makeEventObj = function makeEventObj(self, obj) {
  self.addEventFields(self.context, obj);
  return new Event(obj.type, obj);
};
var forEachEventObj = function forEachEventObj(self, handler, events) {
  if (event(events)) {
    handler(self, events);
    return;
  } else if (plainObject(events)) {
    handler(self, makeEventObj(self, events));
    return;
  }
  var eventList = array(events) ? events : events.split(/\s+/);
  for (var i = 0; i < eventList.length; i++) {
    var evt = eventList[i];
    if (emptyString(evt)) {
      continue;
    }
    var match = evt.match(eventRegex); // type[.namespace]

    if (match) {
      var type = match[1];
      var namespace = match[2] ? match[2] : null;
      var eventObj = makeEventObj(self, {
        type: type,
        namespace: namespace,
        target: self.context
      });
      handler(self, eventObj);
    }
  }
};
p.on = p.addListener = function (events, qualifier, callback, conf, confOverrides) {
  forEachEvent(this, function (self, event, type, namespace, qualifier, callback, conf) {
    if (fn$6(callback)) {
      self.listeners.push({
        event: event,
        // full event string
        callback: callback,
        // callback to run
        type: type,
        // the event type (e.g. 'click')
        namespace: namespace,
        // the event namespace (e.g. ".foo")
        qualifier: qualifier,
        // a restriction on whether to match this emitter
        conf: conf // additional configuration
      });
    }
  }, events, qualifier, callback, conf, confOverrides);
  return this;
};
p.one = function (events, qualifier, callback, conf) {
  return this.on(events, qualifier, callback, conf, {
    one: true
  });
};
p.removeListener = p.off = function (events, qualifier, callback, conf) {
  var _this = this;
  if (this.emitting !== 0) {
    this.listeners = copyArray(this.listeners);
  }
  var listeners = this.listeners;
  var _loop = function _loop(i) {
    var listener = listeners[i];
    forEachEvent(_this, function (self, event, type, namespace, qualifier, callback /*, conf*/) {
      if ((listener.type === type || events === '*') && (!namespace && listener.namespace !== '.*' || listener.namespace === namespace) && (!qualifier || self.qualifierCompare(listener.qualifier, qualifier)) && (!callback || listener.callback === callback)) {
        listeners.splice(i, 1);
        return false;
      }
    }, events, qualifier, callback, conf);
  };
  for (var i = listeners.length - 1; i >= 0; i--) {
    _loop(i);
  }
  return this;
};
p.removeAllListeners = function () {
  return this.removeListener('*');
};
p.emit = p.trigger = function (events, extraParams, manualCallback) {
  var listeners = this.listeners;
  var numListenersBeforeEmit = listeners.length;
  this.emitting++;
  if (!array(extraParams)) {
    extraParams = [extraParams];
  }
  forEachEventObj(this, function (self, eventObj) {
    if (manualCallback != null) {
      listeners = [{
        event: eventObj.event,
        type: eventObj.type,
        namespace: eventObj.namespace,
        callback: manualCallback
      }];
      numListenersBeforeEmit = listeners.length;
    }
    var _loop2 = function _loop2() {
      var listener = listeners[i];
      if (listener.type === eventObj.type && (!listener.namespace || listener.namespace === eventObj.namespace || listener.namespace === universalNamespace) && self.eventMatches(self.context, listener, eventObj)) {
        var args = [eventObj];
        if (extraParams != null) {
          push(args, extraParams);
        }
        self.beforeEmit(self.context, listener, eventObj);
        if (listener.conf && listener.conf.one) {
          self.listeners = self.listeners.filter(function (l) {
            return l !== listener;
          });
        }
        var context = self.callbackContext(self.context, listener, eventObj);
        var ret = listener.callback.apply(context, args);
        self.afterEmit(self.context, listener, eventObj);
        if (ret === false) {
          eventObj.stopPropagation();
          eventObj.preventDefault();
        }
      } // if listener matches
    };
    for (var i = 0; i < numListenersBeforeEmit; i++) {
      _loop2();
    } // for listener

    if (self.bubble(self.context) && !eventObj.isPropagationStopped()) {
      self.parent(self.context).emit(eventObj, extraParams);
    }
  }, events);
  this.emitting--;
  return this;
};

var emitterOptions$1 = {
  qualifierCompare: function qualifierCompare(selector1, selector2) {
    if (selector1 == null || selector2 == null) {
      return selector1 == null && selector2 == null;
    } else {
      return selector1.sameText(selector2);
    }
  },
  eventMatches: function eventMatches(ele, listener, eventObj) {
    var selector = listener.qualifier;
    if (selector != null) {
      return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
    }
    return true;
  },
  addEventFields: function addEventFields(ele, evt) {
    evt.cy = ele.cy();
    evt.target = ele;
  },
  callbackContext: function callbackContext(ele, listener, eventObj) {
    return listener.qualifier != null ? eventObj.target : ele;
  },
  beforeEmit: function beforeEmit(context, listener /*, eventObj*/) {
    if (listener.conf && listener.conf.once) {
      listener.conf.onceCollection.removeListener(listener.event, listener.qualifier, listener.callback);
    }
  },
  bubble: function bubble() {
    return true;
  },
  parent: function parent(ele) {
    return ele.isChild() ? ele.parent() : ele.cy();
  }
};
var argSelector$1 = function argSelector(arg) {
  if (string(arg)) {
    return new Selector(arg);
  } else {
    return arg;
  }
};
var elesfn$9 = {
  createEmitter: function createEmitter() {
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      var _p = ele._private;
      if (!_p.emitter) {
        _p.emitter = new Emitter(emitterOptions$1, ele);
      }
    }
    return this;
  },
  emitter: function emitter() {
    return this._private.emitter;
  },
  on: function on(events, selector, callback) {
    var argSel = argSelector$1(selector);
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      ele.emitter().on(events, argSel, callback);
    }
    return this;
  },
  removeListener: function removeListener(events, selector, callback) {
    var argSel = argSelector$1(selector);
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      ele.emitter().removeListener(events, argSel, callback);
    }
    return this;
  },
  removeAllListeners: function removeAllListeners() {
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      ele.emitter().removeAllListeners();
    }
    return this;
  },
  one: function one(events, selector, callback) {
    var argSel = argSelector$1(selector);
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      ele.emitter().one(events, argSel, callback);
    }
    return this;
  },
  once: function once(events, selector, callback) {
    var argSel = argSelector$1(selector);
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      ele.emitter().on(events, argSel, callback, {
        once: true,
        onceCollection: this
      });
    }
  },
  emit: function emit(events, extraParams) {
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      ele.emitter().emit(events, extraParams);
    }
    return this;
  },
  emitAndNotify: function emitAndNotify(event, extraParams) {
    // for internal use only
    if (this.length === 0) {
      return;
    } // empty collections don't need to notify anything

    // notify renderer
    this.cy().notify(event, this);
    this.emit(event, extraParams);
    return this;
  }
};
define.eventAliasesOn(elesfn$9);

var elesfn$8 = {
  nodes: function nodes(selector) {
    return this.filter(function (ele) {
      return ele.isNode();
    }).filter(selector);
  },
  edges: function edges(selector) {
    return this.filter(function (ele) {
      return ele.isEdge();
    }).filter(selector);
  },
  // internal helper to get nodes and edges as separate collections with single iteration over elements
  byGroup: function byGroup() {
    var nodes = this.spawn();
    var edges = this.spawn();
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      if (ele.isNode()) {
        nodes.push(ele);
      } else {
        edges.push(ele);
      }
    }
    return {
      nodes: nodes,
      edges: edges
    };
  },
  filter: function filter(_filter, thisArg) {
    if (_filter === undefined) {
      // check this first b/c it's the most common/performant case
      return this;
    } else if (string(_filter) || elementOrCollection(_filter)) {
      return new Selector(_filter).filter(this);
    } else if (fn$6(_filter)) {
      var filterEles = this.spawn();
      var eles = this;
      for (var i = 0; i < eles.length; i++) {
        var ele = eles[i];
        var include = thisArg ? _filter.apply(thisArg, [ele, i, eles]) : _filter(ele, i, eles);
        if (include) {
          filterEles.push(ele);
        }
      }
      return filterEles;
    }
    return this.spawn(); // if not handled by above, give 'em an empty collection
  },
  not: function not(toRemove) {
    if (!toRemove) {
      return this;
    } else {
      if (string(toRemove)) {
        toRemove = this.filter(toRemove);
      }
      var elements = this.spawn();
      for (var i = 0; i < this.length; i++) {
        var element = this[i];
        var remove = toRemove.has(element);
        if (!remove) {
          elements.push(element);
        }
      }
      return elements;
    }
  },
  absoluteComplement: function absoluteComplement() {
    var cy = this.cy();
    return cy.mutableElements().not(this);
  },
  intersect: function intersect(other) {
    // if a selector is specified, then filter by it instead
    if (string(other)) {
      var selector = other;
      return this.filter(selector);
    }
    var elements = this.spawn();
    var col1 = this;
    var col2 = other;
    var col1Smaller = this.length < other.length;
    var colS = col1Smaller ? col1 : col2;
    var colL = col1Smaller ? col2 : col1;
    for (var i = 0; i < colS.length; i++) {
      var ele = colS[i];
      if (colL.has(ele)) {
        elements.push(ele);
      }
    }
    return elements;
  },
  xor: function xor(other) {
    var cy = this._private.cy;
    if (string(other)) {
      other = cy.$(other);
    }
    var elements = this.spawn();
    var col1 = this;
    var col2 = other;
    var add = function add(col, other) {
      for (var i = 0; i < col.length; i++) {
        var ele = col[i];
        var id = ele._private.data.id;
        var inOther = other.hasElementWithId(id);
        if (!inOther) {
          elements.push(ele);
        }
      }
    };
    add(col1, col2);
    add(col2, col1);
    return elements;
  },
  diff: function diff(other) {
    var cy = this._private.cy;
    if (string(other)) {
      other = cy.$(other);
    }
    var left = this.spawn();
    var right = this.spawn();
    var both = this.spawn();
    var col1 = this;
    var col2 = other;
    var add = function add(col, other, retEles) {
      for (var i = 0; i < col.length; i++) {
        var ele = col[i];
        var id = ele._private.data.id;
        var inOther = other.hasElementWithId(id);
        if (inOther) {
          both.merge(ele);
        } else {
          retEles.push(ele);
        }
      }
    };
    add(col1, col2, left);
    add(col2, col1, right);
    return {
      left: left,
      right: right,
      both: both
    };
  },
  add: function add(toAdd) {
    var cy = this._private.cy;
    if (!toAdd) {
      return this;
    }
    if (string(toAdd)) {
      var selector = toAdd;
      toAdd = cy.mutableElements().filter(selector);
    }
    var elements = this.spawnSelf();
    for (var i = 0; i < toAdd.length; i++) {
      var ele = toAdd[i];
      var add = !this.has(ele);
      if (add) {
        elements.push(ele);
      }
    }
    return elements;
  },
  // in place merge on calling collection
  merge: function merge(toAdd) {
    var _p = this._private;
    var cy = _p.cy;
    if (!toAdd) {
      return this;
    }
    if (toAdd && string(toAdd)) {
      var selector = toAdd;
      toAdd = cy.mutableElements().filter(selector);
    }
    var map = _p.map;
    for (var i = 0; i < toAdd.length; i++) {
      var toAddEle = toAdd[i];
      var id = toAddEle._private.data.id;
      var add = !map.has(id);
      if (add) {
        var index = this.length++;
        this[index] = toAddEle;
        map.set(id, {
          ele: toAddEle,
          index: index
        });
      }
    }
    return this; // chaining
  },
  unmergeAt: function unmergeAt(i) {
    var ele = this[i];
    var id = ele.id();
    var _p = this._private;
    var map = _p.map;

    // remove ele
    this[i] = undefined;
    map["delete"](id);
    var unmergedLastEle = i === this.length - 1;

    // replace empty spot with last ele in collection
    if (this.length > 1 && !unmergedLastEle) {
      var lastEleI = this.length - 1;
      var lastEle = this[lastEleI];
      var lastEleId = lastEle._private.data.id;
      this[lastEleI] = undefined;
      this[i] = lastEle;
      map.set(lastEleId, {
        ele: lastEle,
        index: i
      });
    }

    // the collection is now 1 ele smaller
    this.length--;
    return this;
  },
  // remove single ele in place in calling collection
  unmergeOne: function unmergeOne(ele) {
    ele = ele[0];
    var _p = this._private;
    var id = ele._private.data.id;
    var map = _p.map;
    var entry = map.get(id);
    if (!entry) {
      return this; // no need to remove
    }
    var i = entry.index;
    this.unmergeAt(i);
    return this;
  },
  // remove eles in place on calling collection
  unmerge: function unmerge(toRemove) {
    var cy = this._private.cy;
    if (!toRemove) {
      return this;
    }
    if (toRemove && string(toRemove)) {
      var selector = toRemove;
      toRemove = cy.mutableElements().filter(selector);
    }
    for (var i = 0; i < toRemove.length; i++) {
      this.unmergeOne(toRemove[i]);
    }
    return this; // chaining
  },
  unmergeBy: function unmergeBy(toRmFn) {
    for (var i = this.length - 1; i >= 0; i--) {
      var ele = this[i];
      if (toRmFn(ele)) {
        this.unmergeAt(i);
      }
    }
    return this;
  },
  map: function map(mapFn, thisArg) {
    var arr = [];
    var eles = this;
    for (var i = 0; i < eles.length; i++) {
      var ele = eles[i];
      var ret = thisArg ? mapFn.apply(thisArg, [ele, i, eles]) : mapFn(ele, i, eles);
      arr.push(ret);
    }
    return arr;
  },
  reduce: function reduce(fn, initialValue) {
    var val = initialValue;
    var eles = this;
    for (var i = 0; i < eles.length; i++) {
      val = fn(val, eles[i], i, eles);
    }
    return val;
  },
  max: function max(valFn, thisArg) {
    var max = -Infinity;
    var maxEle;
    var eles = this;
    for (var i = 0; i < eles.length; i++) {
      var ele = eles[i];
      var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
      if (val > max) {
        max = val;
        maxEle = ele;
      }
    }
    return {
      value: max,
      ele: maxEle
    };
  },
  min: function min(valFn, thisArg) {
    var min = Infinity;
    var minEle;
    var eles = this;
    for (var i = 0; i < eles.length; i++) {
      var ele = eles[i];
      var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
      if (val < min) {
        min = val;
        minEle = ele;
      }
    }
    return {
      value: min,
      ele: minEle
    };
  }
};

// aliases
var fn$1 = elesfn$8;
fn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;
fn$1['\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;
fn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;
fn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;
fn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;
fn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;

var elesfn$7 = {
  isNode: function isNode() {
    return this.group() === 'nodes';
  },
  isEdge: function isEdge() {
    return this.group() === 'edges';
  },
  isLoop: function isLoop() {
    return this.isEdge() && this.source()[0] === this.target()[0];
  },
  isSimple: function isSimple() {
    return this.isEdge() && this.source()[0] !== this.target()[0];
  },
  group: function group() {
    var ele = this[0];
    if (ele) {
      return ele._private.group;
    }
  }
};

/**
 *  Elements are drawn in a specific order based on compound depth (low to high), the element type (nodes above edges),
 *  and z-index (low to high).  These styles affect how this applies:
 *
 *  z-compound-depth: May be `bottom | orphan | auto | top`.  The first drawn is `bottom`, then `orphan` which is the
 *      same depth as the root of the compound graph, followed by the default value `auto` which draws in order from
 *      root to leaves of the compound graph.  The last drawn is `top`.
 *  z-index-compare: May be `auto | manual`.  The default value is `auto` which always draws edges under nodes.
 *      `manual` ignores this convention and draws based on the `z-index` value setting.
 *  z-index: An integer value that affects the relative draw order of elements.  In general, an element with a higher
 *      `z-index` will be drawn on top of an element with a lower `z-index`.
 */
var zIndexSort = function zIndexSort(a, b) {
  var cy = a.cy();
  var hasCompoundNodes = cy.hasCompoundNodes();
  function getDepth(ele) {
    var style = ele.pstyle('z-compound-depth');
    if (style.value === 'auto') {
      return hasCompoundNodes ? ele.zDepth() : 0;
    } else if (style.value === 'bottom') {
      return -1;
    } else if (style.value === 'top') {
      return MAX_INT$1;
    }
    // 'orphan'
    return 0;
  }
  var depthDiff = getDepth(a) - getDepth(b);
  if (depthDiff !== 0) {
    return depthDiff;
  }
  function getEleDepth(ele) {
    var style = ele.pstyle('z-index-compare');
    if (style.value === 'auto') {
      return ele.isNode() ? 1 : 0;
    }
    // 'manual'
    return 0;
  }
  var eleDiff = getEleDepth(a) - getEleDepth(b);
  if (eleDiff !== 0) {
    return eleDiff;
  }
  var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;
  if (zDiff !== 0) {
    return zDiff;
  }
  // compare indices in the core (order added to graph w/ last on top)
  return a.poolIndex() - b.poolIndex();
};

var elesfn$6 = {
  forEach: function forEach(fn, thisArg) {
    if (fn$6(fn)) {
      var N = this.length;
      for (var i = 0; i < N; i++) {
        var ele = this[i];
        var ret = thisArg ? fn.apply(thisArg, [ele, i, this]) : fn(ele, i, this);
        if (ret === false) {
          break;
        } // exit each early on return false
      }
    }
    return this;
  },
  toArray: function toArray() {
    var array = [];
    for (var i = 0; i < this.length; i++) {
      array.push(this[i]);
    }
    return array;
  },
  slice: function slice(start, end) {
    var array = [];
    var thisSize = this.length;
    if (end == null) {
      end = thisSize;
    }
    if (start == null) {
      start = 0;
    }
    if (start < 0) {
      start = thisSize + start;
    }
    if (end < 0) {
      end = thisSize + end;
    }
    for (var i = start; i >= 0 && i < end && i < thisSize; i++) {
      array.push(this[i]);
    }
    return this.spawn(array);
  },
  size: function size() {
    return this.length;
  },
  eq: function eq(i) {
    return this[i] || this.spawn();
  },
  first: function first() {
    return this[0] || this.spawn();
  },
  last: function last() {
    return this[this.length - 1] || this.spawn();
  },
  empty: function empty() {
    return this.length === 0;
  },
  nonempty: function nonempty() {
    return !this.empty();
  },
  sort: function sort(sortFn) {
    if (!fn$6(sortFn)) {
      return this;
    }
    var sorted = this.toArray().sort(sortFn);
    return this.spawn(sorted);
  },
  sortByZIndex: function sortByZIndex() {
    return this.sort(zIndexSort);
  },
  zDepth: function zDepth() {
    var ele = this[0];
    if (!ele) {
      return undefined;
    }

    // let cy = ele.cy();
    var _p = ele._private;
    var group = _p.group;
    if (group === 'nodes') {
      var depth = _p.data.parent ? ele.parents().size() : 0;
      if (!ele.isParent()) {
        return MAX_INT$1 - 1; // childless nodes always on top
      }
      return depth;
    } else {
      var src = _p.source;
      var tgt = _p.target;
      var srcDepth = src.zDepth();
      var tgtDepth = tgt.zDepth();
      return Math.max(srcDepth, tgtDepth, 0); // depth of deepest parent
    }
  }
};
elesfn$6.each = elesfn$6.forEach;
var defineSymbolIterator = function defineSymbolIterator() {
  var typeofUndef = "undefined" ;
  var isIteratorSupported = (typeof Symbol === "undefined" ? "undefined" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef;
  if (isIteratorSupported) {
    elesfn$6[Symbol.iterator] = function () {
      var _this = this;
      var entry = {
        value: undefined,
        done: false
      };
      var i = 0;
      var length = this.length;
      return _defineProperty$1({
        next: function next() {
          if (i < length) {
            entry.value = _this[i++];
          } else {
            entry.value = undefined;
            entry.done = true;
          }
          return entry;
        }
      }, Symbol.iterator, function () {
        return this;
      });
    };
  }
};
defineSymbolIterator();

var getLayoutDimensionOptions = defaults$g({
  nodeDimensionsIncludeLabels: false
});
var elesfn$5 = {
  // Calculates and returns node dimensions { x, y } based on options given
  layoutDimensions: function layoutDimensions(options) {
    options = getLayoutDimensionOptions(options);
    var dims;
    if (!this.takesUpSpace()) {
      dims = {
        w: 0,
        h: 0
      };
    } else if (options.nodeDimensionsIncludeLabels) {
      var bbDim = this.boundingBox();
      dims = {
        w: bbDim.w,
        h: bbDim.h
      };
    } else {
      dims = {
        w: this.outerWidth(),
        h: this.outerHeight()
      };
    }

    // sanitise the dimensions for external layouts (avoid division by zero)
    if (dims.w === 0 || dims.h === 0) {
      dims.w = dims.h = 1;
    }
    return dims;
  },
  // using standard layout options, apply position function (w/ or w/o animation)
  layoutPositions: function layoutPositions(layout, options, fn) {
    var nodes = this.nodes().filter(function (n) {
      return !n.isParent();
    });
    var cy = this.cy();
    var layoutEles = options.eles; // nodes & edges
    var getMemoizeKey = function getMemoizeKey(node) {
      return node.id();
    };
    var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function

    layout.emit({
      type: 'layoutstart',
      layout: layout
    });
    layout.animations = [];
    var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) {
      var center = {
        x: nodesBb.x1 + nodesBb.w / 2,
        y: nodesBb.y1 + nodesBb.h / 2
      };
      var spacingVector = {
        // scale from center of bounding box (not necessarily 0,0)
        x: (pos.x - center.x) * spacing,
        y: (pos.y - center.y) * spacing
      };
      return {
        x: center.x + spacingVector.x,
        y: center.y + spacingVector.y
      };
    };
    var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;
    var spacingBb = function spacingBb() {
      if (!useSpacingFactor) {
        return null;
      }
      var bb = makeBoundingBox();
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var pos = fnMem(node, i);
        expandBoundingBoxByPoint(bb, pos.x, pos.y);
      }
      return bb;
    };
    var bb = spacingBb();
    var getFinalPos = memoize(function (node, i) {
      var newPos = fnMem(node, i);
      if (useSpacingFactor) {
        var spacing = Math.abs(options.spacingFactor);
        newPos = calculateSpacing(spacing, bb, newPos);
      }
      if (options.transform != null) {
        newPos = options.transform(node, newPos);
      }
      return newPos;
    }, getMemoizeKey);
    if (options.animate) {
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var newPos = getFinalPos(node, i);
        var animateNode = options.animateFilter == null || options.animateFilter(node, i);
        if (animateNode) {
          var ani = node.animation({
            position: newPos,
            duration: options.animationDuration,
            easing: options.animationEasing
          });
          layout.animations.push(ani);
        } else {
          node.position(newPos);
        }
      }
      if (options.fit) {
        var fitAni = cy.animation({
          fit: {
            boundingBox: layoutEles.boundingBoxAt(getFinalPos),
            padding: options.padding
          },
          duration: options.animationDuration,
          easing: options.animationEasing
        });
        layout.animations.push(fitAni);
      } else if (options.zoom !== undefined && options.pan !== undefined) {
        var zoomPanAni = cy.animation({
          zoom: options.zoom,
          pan: options.pan,
          duration: options.animationDuration,
          easing: options.animationEasing
        });
        layout.animations.push(zoomPanAni);
      }
      layout.animations.forEach(function (ani) {
        return ani.play();
      });
      layout.one('layoutready', options.ready);
      layout.emit({
        type: 'layoutready',
        layout: layout
      });
      Promise$1.all(layout.animations.map(function (ani) {
        return ani.promise();
      })).then(function () {
        layout.one('layoutstop', options.stop);
        layout.emit({
          type: 'layoutstop',
          layout: layout
        });
      });
    } else {
      nodes.positions(getFinalPos);
      if (options.fit) {
        cy.fit(options.eles, options.padding);
      }
      if (options.zoom != null) {
        cy.zoom(options.zoom);
      }
      if (options.pan) {
        cy.pan(options.pan);
      }
      layout.one('layoutready', options.ready);
      layout.emit({
        type: 'layoutready',
        layout: layout
      });
      layout.one('layoutstop', options.stop);
      layout.emit({
        type: 'layoutstop',
        layout: layout
      });
    }
    return this; // chaining
  },
  layout: function layout(options) {
    var cy = this.cy();
    return cy.makeLayout(extend({}, options, {
      eles: this
    }));
  }
};

// aliases:
elesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;

function styleCache(key, fn, ele) {
  var _p = ele._private;
  var cache = _p.styleCache = _p.styleCache || [];
  var val;
  if ((val = cache[key]) != null) {
    return val;
  } else {
    val = cache[key] = fn(ele);
    return val;
  }
}
function cacheStyleFunction(key, fn) {
  key = hashString(key);
  return function cachedStyleFunction(ele) {
    return styleCache(key, fn, ele);
  };
}
function cachePrototypeStyleFunction(key, fn) {
  key = hashString(key);
  var selfFn = function selfFn(ele) {
    return fn.call(ele);
  };
  return function cachedPrototypeStyleFunction() {
    var ele = this[0];
    if (ele) {
      return styleCache(key, selfFn, ele);
    }
  };
}
var elesfn$4 = {
  recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {
    var cy = this.cy();
    var renderer = cy.renderer();
    var styleEnabled = cy.styleEnabled();
    if (renderer && styleEnabled) {
      renderer.recalculateRenderedStyle(this, useCache);
    }
    return this;
  },
  dirtyStyleCache: function dirtyStyleCache() {
    var cy = this.cy();
    var dirty = function dirty(ele) {
      return ele._private.styleCache = null;
    };
    if (cy.hasCompoundNodes()) {
      var eles;
      eles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
      eles.merge(eles.connectedEdges());
      eles.forEach(dirty);
    } else {
      this.forEach(function (ele) {
        dirty(ele);
        ele.connectedEdges().forEach(dirty);
      });
    }
    return this;
  },
  // fully updates (recalculates) the style for the elements
  updateStyle: function updateStyle(notifyRenderer) {
    var cy = this._private.cy;
    if (!cy.styleEnabled()) {
      return this;
    }
    if (cy.batching()) {
      var bEles = cy._private.batchStyleEles;
      bEles.merge(this);
      return this; // chaining and exit early when batching
    }
    var hasCompounds = cy.hasCompoundNodes();
    var updatedEles = this;
    notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;
    if (hasCompounds) {
      // then add everything up and down for compound selector checks
      updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
    }

    // let changedEles = style.apply( updatedEles );
    var changedEles = updatedEles;
    if (notifyRenderer) {
      changedEles.emitAndNotify('style'); // let renderer know we changed style
    } else {
      changedEles.emit('style'); // just fire the event
    }
    updatedEles.forEach(function (ele) {
      return ele._private.styleDirty = true;
    });
    return this; // chaining
  },
  // private: clears dirty flag and recalculates style
  cleanStyle: function cleanStyle() {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return;
    }
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      if (ele._private.styleDirty) {
        // n.b. this flag should be set before apply() to avoid potential infinite recursion
        ele._private.styleDirty = false;
        cy.style().apply(ele);
      }
    }
  },
  // get the internal parsed style object for the specified property
  parsedStyle: function parsedStyle(property) {
    var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    var ele = this[0];
    var cy = ele.cy();
    if (!cy.styleEnabled()) {
      return;
    }
    if (ele) {
      // this.cleanStyle();

      // Inline the important part of cleanStyle(), for raw performance
      if (ele._private.styleDirty) {
        // n.b. this flag should be set before apply() to avoid potential infinite recursion
        ele._private.styleDirty = false;
        cy.style().apply(ele);
      }
      var overriddenStyle = ele._private.style[property];
      if (overriddenStyle != null) {
        return overriddenStyle;
      } else if (includeNonDefault) {
        return cy.style().getDefaultProperty(property);
      } else {
        return null;
      }
    }
  },
  numericStyle: function numericStyle(property) {
    var ele = this[0];
    if (!ele.cy().styleEnabled()) {
      return;
    }
    if (ele) {
      var pstyle = ele.pstyle(property);
      return pstyle.pfValue !== undefined ? pstyle.pfValue : pstyle.value;
    }
  },
  numericStyleUnits: function numericStyleUnits(property) {
    var ele = this[0];
    if (!ele.cy().styleEnabled()) {
      return;
    }
    if (ele) {
      return ele.pstyle(property).units;
    }
  },
  // get the specified css property as a rendered value (i.e. on-screen value)
  // or get the whole rendered style if no property specified (NB doesn't allow setting)
  renderedStyle: function renderedStyle(property) {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return this;
    }
    var ele = this[0];
    if (ele) {
      return cy.style().getRenderedStyle(ele, property);
    }
  },
  // read the calculated css style of the element or override the style (via a bypass)
  style: function style(name, value) {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return this;
    }
    var updateTransitions = false;
    var style = cy.style();
    if (plainObject(name)) {
      // then extend the bypass
      var props = name;
      style.applyBypass(this, props, updateTransitions);
      this.emitAndNotify('style'); // let the renderer know we've updated style
    } else if (string(name)) {
      if (value === undefined) {
        // then get the property from the style
        var ele = this[0];
        if (ele) {
          return style.getStylePropertyValue(ele, name);
        } else {
          // empty collection => can't get any value
          return;
        }
      } else {
        // then set the bypass with the property value
        style.applyBypass(this, name, value, updateTransitions);
        this.emitAndNotify('style'); // let the renderer know we've updated style
      }
    } else if (name === undefined) {
      var _ele = this[0];
      if (_ele) {
        return style.getRawStyle(_ele);
      } else {
        // empty collection => can't get any value
        return;
      }
    }
    return this; // chaining
  },
  removeStyle: function removeStyle(names) {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return this;
    }
    var updateTransitions = false;
    var style = cy.style();
    var eles = this;
    if (names === undefined) {
      for (var i = 0; i < eles.length; i++) {
        var ele = eles[i];
        style.removeAllBypasses(ele, updateTransitions);
      }
    } else {
      names = names.split(/\s+/);
      for (var _i = 0; _i < eles.length; _i++) {
        var _ele2 = eles[_i];
        style.removeBypasses(_ele2, names, updateTransitions);
      }
    }
    this.emitAndNotify('style'); // let the renderer know we've updated style

    return this; // chaining
  },
  show: function show() {
    this.css('display', 'element');
    return this; // chaining
  },
  hide: function hide() {
    this.css('display', 'none');
    return this; // chaining
  },
  effectiveOpacity: function effectiveOpacity() {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return 1;
    }
    var hasCompoundNodes = cy.hasCompoundNodes();
    var ele = this[0];
    if (ele) {
      var _p = ele._private;
      var parentOpacity = ele.pstyle('opacity').value;
      if (!hasCompoundNodes) {
        return parentOpacity;
      }
      var parents = !_p.data.parent ? null : ele.parents();
      if (parents) {
        for (var i = 0; i < parents.length; i++) {
          var parent = parents[i];
          var opacity = parent.pstyle('opacity').value;
          parentOpacity = opacity * parentOpacity;
        }
      }
      return parentOpacity;
    }
  },
  transparent: function transparent() {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return false;
    }
    var ele = this[0];
    var hasCompoundNodes = ele.cy().hasCompoundNodes();
    if (ele) {
      if (!hasCompoundNodes) {
        return ele.pstyle('opacity').value === 0;
      } else {
        return ele.effectiveOpacity() === 0;
      }
    }
  },
  backgrounding: function backgrounding() {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return false;
    }
    var ele = this[0];
    return ele._private.backgrounding ? true : false;
  }
};
function checkCompound(ele, parentOk) {
  var _p = ele._private;
  var parents = _p.data.parent ? ele.parents() : null;
  if (parents) {
    for (var i = 0; i < parents.length; i++) {
      var parent = parents[i];
      if (!parentOk(parent)) {
        return false;
      }
    }
  }
  return true;
}
function defineDerivedStateFunction(specs) {
  var ok = specs.ok;
  var edgeOkViaNode = specs.edgeOkViaNode || specs.ok;
  var parentOk = specs.parentOk || specs.ok;
  return function () {
    var cy = this.cy();
    if (!cy.styleEnabled()) {
      return true;
    }
    var ele = this[0];
    var hasCompoundNodes = cy.hasCompoundNodes();
    if (ele) {
      var _p = ele._private;
      if (!ok(ele)) {
        return false;
      }
      if (ele.isNode()) {
        return !hasCompoundNodes || checkCompound(ele, parentOk);
      } else {
        var src = _p.source;
        var tgt = _p.target;
        return edgeOkViaNode(src) && (!hasCompoundNodes || checkCompound(src, edgeOkViaNode)) && (src === tgt || edgeOkViaNode(tgt) && (!hasCompoundNodes || checkCompound(tgt, edgeOkViaNode)));
      }
    }
  };
}
var eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {
  return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);
});
elesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({
  ok: eleTakesUpSpace
}));
var eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {
  return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);
});
var parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {
  return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);
});
elesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({
  ok: eleInteractive,
  parentOk: parentInteractive,
  edgeOkViaNode: eleTakesUpSpace
}));
elesfn$4.noninteractive = function () {
  var ele = this[0];
  if (ele) {
    return !ele.interactive();
  }
};
var eleVisible = cacheStyleFunction('eleVisible', function (ele) {
  return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);
});
var edgeVisibleViaNode = eleTakesUpSpace;
elesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({
  ok: eleVisible,
  edgeOkViaNode: edgeVisibleViaNode
}));
elesfn$4.hidden = function () {
  var ele = this[0];
  if (ele) {
    return !ele.visible();
  }
};
elesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {
  if (!this.cy().styleEnabled()) {
    return false;
  }
  return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();
});
elesfn$4.bypass = elesfn$4.css = elesfn$4.style;
elesfn$4.renderedCss = elesfn$4.renderedStyle;
elesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;
elesfn$4.pstyle = elesfn$4.parsedStyle;

var elesfn$3 = {};
function defineSwitchFunction(params) {
  return function () {
    var args = arguments;
    var changedEles = [];

    // e.g. cy.nodes().select( data, handler )
    if (args.length === 2) {
      var data = args[0];
      var handler = args[1];
      this.on(params.event, data, handler);
    }

    // e.g. cy.nodes().select( handler )
    else if (args.length === 1 && fn$6(args[0])) {
      var _handler = args[0];
      this.on(params.event, _handler);
    }

    // e.g. cy.nodes().select()
    // e.g. (private) cy.nodes().select(['tapselect'])
    else if (args.length === 0 || args.length === 1 && array(args[0])) {
      var addlEvents = args.length === 1 ? args[0] : null;
      for (var i = 0; i < this.length; i++) {
        var ele = this[i];
        var able = !params.ableField || ele._private[params.ableField];
        var changed = ele._private[params.field] != params.value;
        if (params.overrideAble) {
          var overrideAble = params.overrideAble(ele);
          if (overrideAble !== undefined) {
            able = overrideAble;
            if (!overrideAble) {
              return this;
            } // to save cycles assume not able for all on override
          }
        }
        if (able) {
          ele._private[params.field] = params.value;
          if (changed) {
            changedEles.push(ele);
          }
        }
      }
      var changedColl = this.spawn(changedEles);
      changedColl.updateStyle(); // change of state => possible change of style
      changedColl.emit(params.event);
      if (addlEvents) {
        changedColl.emit(addlEvents);
      }
    }
    return this;
  };
}
function defineSwitchSet(params) {
  elesfn$3[params.field] = function () {
    var ele = this[0];
    if (ele) {
      if (params.overrideField) {
        var val = params.overrideField(ele);
        if (val !== undefined) {
          return val;
        }
      }
      return ele._private[params.field];
    }
  };
  elesfn$3[params.on] = defineSwitchFunction({
    event: params.on,
    field: params.field,
    ableField: params.ableField,
    overrideAble: params.overrideAble,
    value: true
  });
  elesfn$3[params.off] = defineSwitchFunction({
    event: params.off,
    field: params.field,
    ableField: params.ableField,
    overrideAble: params.overrideAble,
    value: false
  });
}
defineSwitchSet({
  field: 'locked',
  overrideField: function overrideField(ele) {
    return ele.cy().autolock() ? true : undefined;
  },
  on: 'lock',
  off: 'unlock'
});
defineSwitchSet({
  field: 'grabbable',
  overrideField: function overrideField(ele) {
    return ele.cy().autoungrabify() || ele.pannable() ? false : undefined;
  },
  on: 'grabify',
  off: 'ungrabify'
});
defineSwitchSet({
  field: 'selected',
  ableField: 'selectable',
  overrideAble: function overrideAble(ele) {
    return ele.cy().autounselectify() ? false : undefined;
  },
  on: 'select',
  off: 'unselect'
});
defineSwitchSet({
  field: 'selectable',
  overrideField: function overrideField(ele) {
    return ele.cy().autounselectify() ? false : undefined;
  },
  on: 'selectify',
  off: 'unselectify'
});
elesfn$3.deselect = elesfn$3.unselect;
elesfn$3.grabbed = function () {
  var ele = this[0];
  if (ele) {
    return ele._private.grabbed;
  }
};
defineSwitchSet({
  field: 'active',
  on: 'activate',
  off: 'unactivate'
});
defineSwitchSet({
  field: 'pannable',
  on: 'panify',
  off: 'unpanify'
});
elesfn$3.inactive = function () {
  var ele = this[0];
  if (ele) {
    return !ele._private.active;
  }
};

var elesfn$2 = {};

// DAG functions
////////////////

var defineDagExtremity = function defineDagExtremity(params) {
  return function dagExtremityImpl(selector) {
    var eles = this;
    var ret = [];
    for (var i = 0; i < eles.length; i++) {
      var ele = eles[i];
      if (!ele.isNode()) {
        continue;
      }
      var disqualified = false;
      var edges = ele.connectedEdges();
      for (var j = 0; j < edges.length; j++) {
        var edge = edges[j];
        var src = edge.source();
        var tgt = edge.target();
        if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {
          disqualified = true;
          break;
        }
      }
      if (!disqualified) {
        ret.push(ele);
      }
    }
    return this.spawn(ret, true).filter(selector);
  };
};
var defineDagOneHop = function defineDagOneHop(params) {
  return function (selector) {
    var eles = this;
    var oEles = [];
    for (var i = 0; i < eles.length; i++) {
      var ele = eles[i];
      if (!ele.isNode()) {
        continue;
      }
      var edges = ele.connectedEdges();
      for (var j = 0; j < edges.length; j++) {
        var edge = edges[j];
        var src = edge.source();
        var tgt = edge.target();
        if (params.outgoing && src === ele) {
          oEles.push(edge);
          oEles.push(tgt);
        } else if (params.incoming && tgt === ele) {
          oEles.push(edge);
          oEles.push(src);
        }
      }
    }
    return this.spawn(oEles, true).filter(selector);
  };
};
var defineDagAllHops = function defineDagAllHops(params) {
  return function (selector) {
    var eles = this;
    var sEles = [];
    var sElesIds = {};
    for (;;) {
      var next = params.outgoing ? eles.outgoers() : eles.incomers();
      if (next.length === 0) {
        break;
      } // done if none left

      var newNext = false;
      for (var i = 0; i < next.length; i++) {
        var n = next[i];
        var nid = n.id();
        if (!sElesIds[nid]) {
          sElesIds[nid] = true;
          sEles.push(n);
          newNext = true;
        }
      }
      if (!newNext) {
        break;
      } // done if touched all outgoers already

      eles = next;
    }
    return this.spawn(sEles, true).filter(selector);
  };
};
elesfn$2.clearTraversalCache = function () {
  for (var i = 0; i < this.length; i++) {
    this[i]._private.traversalCache = null;
  }
};
extend(elesfn$2, {
  // get the root nodes in the DAG
  roots: defineDagExtremity({
    noIncomingEdges: true
  }),
  // get the leaf nodes in the DAG
  leaves: defineDagExtremity({
    noOutgoingEdges: true
  }),
  // normally called children in graph theory
  // these nodes =edges=> outgoing nodes
  outgoers: cache(defineDagOneHop({
    outgoing: true
  }), 'outgoers'),
  // aka DAG descendants
  successors: defineDagAllHops({
    outgoing: true
  }),
  // normally called parents in graph theory
  // these nodes <=edges= incoming nodes
  incomers: cache(defineDagOneHop({
    incoming: true
  }), 'incomers'),
  // aka DAG ancestors
  predecessors: defineDagAllHops({
    })
});

// Neighbourhood functions
//////////////////////////

extend(elesfn$2, {
  neighborhood: cache(function (selector) {
    var elements = [];
    var nodes = this.nodes();
    for (var i = 0; i < nodes.length; i++) {
      // for all nodes
      var node = nodes[i];
      var connectedEdges = node.connectedEdges();

      // for each connected edge, add the edge and the other node
      for (var j = 0; j < connectedEdges.length; j++) {
        var edge = connectedEdges[j];
        var src = edge.source();
        var tgt = edge.target();
        var otherNode = node === src ? tgt : src;

        // need check in case of loop
        if (otherNode.length > 0) {
          elements.push(otherNode[0]); // add node 1 hop away
        }

        // add connected edge
        elements.push(edge[0]);
      }
    }
    return this.spawn(elements, true).filter(selector);
  }, 'neighborhood'),
  closedNeighborhood: function closedNeighborhood(selector) {
    return this.neighborhood().add(this).filter(selector);
  },
  openNeighborhood: function openNeighborhood(selector) {
    return this.neighborhood(selector);
  }
});

// aliases
elesfn$2.neighbourhood = elesfn$2.neighborhood;
elesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;
elesfn$2.openNeighbourhood = elesfn$2.openNeighborhood;

// Edge functions
/////////////////

extend(elesfn$2, {
  source: cache(function sourceImpl(selector) {
    var ele = this[0];
    var src;
    if (ele) {
      src = ele._private.source || ele.cy().collection();
    }
    return src && selector ? src.filter(selector) : src;
  }, 'source'),
  target: cache(function targetImpl(selector) {
    var ele = this[0];
    var tgt;
    if (ele) {
      tgt = ele._private.target || ele.cy().collection();
    }
    return tgt && selector ? tgt.filter(selector) : tgt;
  }, 'target'),
  sources: defineSourceFunction({
    attr: 'source'
  }),
  targets: defineSourceFunction({
    attr: 'target'
  })
});
function defineSourceFunction(params) {
  return function sourceImpl(selector) {
    var sources = [];
    for (var i = 0; i < this.length; i++) {
      var ele = this[i];
      var src = ele._private[params.attr];
      if (src) {
        sources.push(src);
      }
    }
    return this.spawn(sources, true).filter(selector);
  };
}
extend(elesfn$2, {
  edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),
  edgesTo: cache(defineEdgesWithFunction({
    thisIsSrc: true
  }), 'edgesTo')
});
function defineEdgesWithFunction(params) {
  return function edgesWithImpl(otherNodes) {
    var elements = [];
    var cy = this._private.cy;
    var p = params || {};

    // get elements if a selector is specified
    if (string(otherNodes)) {
      otherNodes = cy.$(otherNodes);
    }
    for (var h = 0; h < otherNodes.length; h++) {
      var edges = otherNodes[h]._private.edges;
      for (var i = 0; i < edges.length; i++) {
        var edge = edges[i];
        var edgeData = edge._private.data;
        var thisToOther = this.hasElementWithId(edgeData.source) && otherNodes.hasElementWithId(edgeData.target);
        var otherToThis = otherNodes.hasElementWithId(edgeData.source) && this.hasElementWithId(edgeData.target);
        var edgeConnectsThisAndOther = thisToOther || otherToThis;
        if (!edgeConnectsThisAndOther) {
          continue;
        }
        if (p.thisIsSrc || p.thisIsTgt) {
          if (p.thisIsSrc && !thisToOther) {
            continue;
          }
          if (p.thisIsTgt && !otherToThis) {
            continue;
          }
        }
        elements.push(edge);
      }
    }
    return this.spawn(elements, true);
  };
}
extend(elesfn$2, {
  connectedEdges: cache(function (selector) {
    var retEles = [];
    var eles = this;
    for (var i = 0; i < eles.length; i++) {
      var node = eles[i];
      if (!node.isNode()) {
        continue;
      }
      var edges = node._private.edges;
      for (var j = 0; j < edges.length; j++) {
        var edge = edges[j];
        retEles.push(edge);
      }
    }
    return this.spawn(retEles, true).filter(selector);
  }, 'connectedEdges'),
  connectedNodes: cache(function (selector) {
    var retEles = [];
    var eles = this;
    for (var i = 0; i < eles.length; i++) {
      var edge = eles[i];
      if (!edge.isEdge()) {
        continue;
      }
      retEles.push(edge.source()[0]);
      retEles.push(edge.target()[0]);
    }
    return this.spawn(retEles, true).filter(selector);
  }, 'connectedNodes'),
  parallelEdges: cache(defineParallelEdgesFunction(), 'parallelEdges'),
  codirectedEdges: cache(defineParallelEdgesFunction({
    codirected: true
  }), 'codirectedEdges')
});
function defineParallelEdgesFunction(params) {
  var defaults = {
    codirected: false
  };
  params = extend({}, defaults, params);
  return function parallelEdgesImpl(selector) {
    // micro-optimised for renderer
    var elements = [];
    var edges = this.edges();
    var p = params;

    // look at all the edges in the collection
    for (var i = 0; i < edges.length; i++) {
      var edge1 = edges[i];
      var edge1_p = edge1._private;
      var src1 = edge1_p.source;
      var srcid1 = src1._private.data.id;
      var tgtid1 = edge1_p.data.target;
      var srcEdges1 = src1._private.edges;

      // look at edges connected to the src node of this edge
      for (var j = 0; j < srcEdges1.length; j++) {
        var edge2 = srcEdges1[j];
        var edge2data = edge2._private.data;
        var tgtid2 = edge2data.target;
        var srcid2 = edge2data.source;
        var codirected = tgtid2 === tgtid1 && srcid2 === srcid1;
        var oppdirected = srcid1 === tgtid2 && tgtid1 === srcid2;
        if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {
          elements.push(edge2);
        }
      }
    }
    return this.spawn(elements, true).filter(selector);
  };
}

// Misc functions
/////////////////

extend(elesfn$2, {
  components: function components(root) {
    var self = this;
    var cy = self.cy();
    var visited = cy.collection();
    var unvisited = root == null ? self.nodes() : root.nodes();
    var components = [];
    if (root != null && unvisited.empty()) {
      // root may contain only edges
      unvisited = root.sources(); // doesn't matter which node to use (undirected), so just use the source sides
    }
    var visitInComponent = function visitInComponent(node, component) {
      visited.merge(node);
      unvisited.unmerge(node);
      component.merge(node);
    };
    if (unvisited.empty()) {
      return self.spawn();
    }
    var _loop = function _loop() {
      // each iteration yields a component
      var cmpt = cy.collection();
      components.push(cmpt);
      var root = unvisited[0];
      visitInComponent(root, cmpt);
      self.bfs({
        directed: false,
        roots: root,
        visit: function visit(v) {
          return visitInComponent(v, cmpt);
        }
      });
      cmpt.forEach(function (node) {
        node.connectedEdges().forEach(function (e) {
          // connectedEdges() usually cached
          if (self.has(e) && cmpt.has(e.source()) && cmpt.has(e.target())) {
            // has() is cheap
            cmpt.merge(e); // forEach() only considers nodes -- sets N at call time
          }
        });
      });
    };
    do {
      _loop();
    } while (unvisited.length > 0);
    return components;
  },
  component: function component() {
    var ele = this[0];
    return ele.cy().mutableElements().components(ele)[0];
  }
});
elesfn$2.componentsOf = elesfn$2.components;

// represents a set of nodes, edges, or both together
var Collection = function Collection(cy, elements) {
  var unique = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  var removed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  if (cy === undefined) {
    error('A collection must have a reference to the core');
    return;
  }
  var map = new Map$1();
  var createdElements = false;
  if (!elements) {
    elements = [];
  } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {
    createdElements = true;

    // make elements from json and restore all at once later
    var eles = [];
    var elesIds = new Set$1();
    for (var i = 0, l = elements.length; i < l; i++) {
      var json = elements[i];
      if (json.data == null) {
        json.data = {};
      }
      var _data = json.data;

      // make sure newly created elements have valid ids
      if (_data.id == null) {
        _data.id = uuid();
      } else if (cy.hasElementWithId(_data.id) || elesIds.has(_data.id)) {
        continue; // can't create element if prior id already exists
      }
      var ele = new Element(cy, json, false);
      eles.push(ele);
      elesIds.add(_data.id);
    }
    elements = eles;
  }
  this.length = 0;
  for (var _i = 0, _l = elements.length; _i < _l; _i++) {
    var element$1 = elements[_i][0]; // [0] in case elements is an array of collections, rather than array of elements
    if (element$1 == null) {
      continue;
    }
    var id = element$1._private.data.id;
    if (!unique || !map.has(id)) {
      if (unique) {
        map.set(id, {
          index: this.length,
          ele: element$1
        });
      }
      this[this.length] = element$1;
      this.length++;
    }
  }
  this._private = {
    eles: this,
    cy: cy,
    get map() {
      if (this.lazyMap == null) {
        this.rebuildMap();
      }
      return this.lazyMap;
    },
    set map(m) {
      this.lazyMap = m;
    },
    rebuildMap: function rebuildMap() {
      var m = this.lazyMap = new Map$1();
      var eles = this.eles;
      for (var _i2 = 0; _i2 < eles.length; _i2++) {
        var _ele = eles[_i2];
        m.set(_ele.id(), {
          index: _i2,
          ele: _ele
        });
      }
    }
  };
  if (unique) {
    this._private.map = map;
  }

  // restore the elements if we created them from json
  if (createdElements && !removed) {
    this.restore();
  }
};

// Functions
////////////////////////////////////////////////////////////////////////////////////////////////////

// keep the prototypes in sync (an element has the same functions as a collection)
// and use elefn and elesfn as shorthands to the prototypes
var elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);
elesfn$1.instanceString = function () {
  return 'collection';
};
elesfn$1.spawn = function (eles, unique) {
  return new Collection(this.cy(), eles, unique);
};
elesfn$1.spawnSelf = function () {
  return this.spawn(this);
};
elesfn$1.cy = function () {
  return this._private.cy;
};
elesfn$1.renderer = function () {
  return this._private.cy.renderer();
};
elesfn$1.element = function () {
  return this[0];
};
elesfn$1.collection = function () {
  if (collection(this)) {
    return this;
  } else {
    // an element
    return new Collection(this._private.cy, [this]);
  }
};
elesfn$1.unique = function () {
  return new Collection(this._private.cy, this, true);
};
elesfn$1.hasElementWithId = function (id) {
  id = '' + id; // id must be string

  return this._private.map.has(id);
};
elesfn$1.getElementById = function (id) {
  id = '' + id; // id must be string

  var cy = this._private.cy;
  var entry = this._private.map.get(id);
  return entry ? entry.ele : new Collection(cy); // get ele or empty collection
};
elesfn$1.$id = elesfn$1.getElementById;
elesfn$1.poolIndex = function () {
  var cy = this._private.cy;
  var eles = cy._private.elements;
  var id = this[0]._private.data.id;
  return eles._private.map.get(id).index;
};
elesfn$1.indexOf = function (ele) {
  var id = ele[0]._private.data.id;
  return this._private.map.get(id).index;
};
elesfn$1.indexOfId = function (id) {
  id = '' + id; // id must be string

  return this._private.map.get(id).index;
};
elesfn$1.json = function (obj) {
  var ele = this.element();
  var cy = this.cy();
  if (ele == null && obj) {
    return this;
  } // can't set to no eles

  if (ele == null) {
    return undefined;
  } // can't get from no eles

  var p = ele._private;
  if (plainObject(obj)) {
    // set

    cy.startBatch();
    if (obj.data) {
      ele.data(obj.data);
      var _data2 = p.data;
      if (ele.isEdge()) {
        // source and target are immutable via data()
        var move = false;
        var spec = {};
        var src = obj.data.source;
        var tgt = obj.data.target;
        if (src != null && src != _data2.source) {
          spec.source = '' + src; // id must be string
          move = true;
        }
        if (tgt != null && tgt != _data2.target) {
          spec.target = '' + tgt; // id must be string
          move = true;
        }
        if (move) {
          ele = ele.move(spec);
        }
      } else {
        // parent is immutable via data()
        var newParentValSpecd = 'parent' in obj.data;
        var parent = obj.data.parent;
        if (newParentValSpecd && (parent != null || _data2.parent != null) && parent != _data2.parent) {
          if (parent === undefined) {
            // can't set undefined imperatively, so use null
            parent = null;
          }
          if (parent != null) {
            parent = '' + parent; // id must be string
          }
          ele = ele.move({
            parent: parent
          });
        }
      }
    }
    if (obj.position) {
      ele.position(obj.position);
    }

    // ignore group -- immutable

    var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {
      var obj_k = obj[k];
      if (obj_k != null && obj_k !== p[k]) {
        if (obj_k) {
          ele[trueFnName]();
        } else {
          ele[falseFnName]();
        }
      }
    };
    checkSwitch('removed', 'remove', 'restore');
    checkSwitch('selected', 'select', 'unselect');
    checkSwitch('selectable', 'selectify', 'unselectify');
    checkSwitch('locked', 'lock', 'unlock');
    checkSwitch('grabbable', 'grabify', 'ungrabify');
    checkSwitch('pannable', 'panify', 'unpanify');
    if (obj.classes != null) {
      ele.classes(obj.classes);
    }
    cy.endBatch();
    return this;
  } else if (obj === undefined) {
    // get

    var json = {
      data: copy(p.data),
      position: copy(p.position),
      group: p.group,
      removed: p.removed,
      selected: p.selected,
      selectable: p.selectable,
      locked: p.locked,
      grabbable: p.grabbable,
      pannable: p.pannable,
      classes: null
    };
    json.classes = '';
    var i = 0;
    p.classes.forEach(function (cls) {
      return json.classes += i++ === 0 ? cls : ' ' + cls;
    });
    return json;
  }
};
elesfn$1.jsons = function () {
  var jsons = [];
  for (var i = 0; i < this.length; i++) {
    var ele = this[i];
    var json = ele.json();
    jsons.push(json);
  }
  return jsons;
};
elesfn$1.clone = function () {
  var cy = this.cy();
  var elesArr = [];
  for (var i = 0; i < this.length; i++) {
    var ele = this[i];
    var json = ele.json();
    var clone = new Element(cy, json, false); // NB no restore

    elesArr.push(clone);
  }
  return new Collection(cy, elesArr);
};
elesfn$1.copy = elesfn$1.clone;
elesfn$1.restore = function () {
  var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  var addToPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var self = this;
  var cy = self.cy();
  var cy_p = cy._private;

  // create arrays of nodes and edges, since we need to
  // restore the nodes first
  var nodes = [];
  var edges = [];
  var elements;
  for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {
    var ele = self[_i3];
    if (addToPool && !ele.removed()) {
      // don't need to handle this ele
      continue;
    }

    // keep nodes first in the array and edges after
    if (ele.isNode()) {
      // put to front of array if node
      nodes.push(ele);
    } else {
      // put to end of array if edge
      edges.push(ele);
    }
  }
  elements = nodes.concat(edges);
  var i;
  var removeFromElements = function removeFromElements() {
    elements.splice(i, 1);
    i--;
  };

  // now, restore each element
  for (i = 0; i < elements.length; i++) {
    var _ele2 = elements[i];
    var _private = _ele2._private;
    var _data3 = _private.data;

    // the traversal cache should start fresh when ele is added
    _ele2.clearTraversalCache();

    // set id and validate
    if (!addToPool && !_private.removed) ; else if (_data3.id === undefined) {
      _data3.id = uuid();
    } else if (number$1(_data3.id)) {
      _data3.id = '' + _data3.id; // now it's a string
    } else if (emptyString(_data3.id) || !string(_data3.id)) {
      error('Can not create element with invalid string ID `' + _data3.id + '`');

      // can't create element if it has empty string as id or non-string id
      removeFromElements();
      continue;
    } else if (cy.hasElementWithId(_data3.id)) {
      error('Can not create second element with ID `' + _data3.id + '`');

      // can't create element if one already has that id
      removeFromElements();
      continue;
    }
    var id = _data3.id; // id is finalised, now let's keep a ref

    if (_ele2.isNode()) {
      // extra checks for nodes
      var pos = _private.position;

      // make sure the nodes have a defined position

      if (pos.x == null) {
        pos.x = 0;
      }
      if (pos.y == null) {
        pos.y = 0;
      }
    }
    if (_ele2.isEdge()) {
      // extra checks for edges

      var edge = _ele2;
      var fields = ['source', 'target'];
      var fieldsLength = fields.length;
      var badSourceOrTarget = false;
      for (var j = 0; j < fieldsLength; j++) {
        var field = fields[j];
        var val = _data3[field];
        if (number$1(val)) {
          val = _data3[field] = '' + _data3[field]; // now string
        }
        if (val == null || val === '') {
          // can't create if source or target is not defined properly
          error('Can not create edge `' + id + '` with unspecified ' + field);
          badSourceOrTarget = true;
        } else if (!cy.hasElementWithId(val)) {
          // can't create edge if one of its nodes doesn't exist
          error('Can not create edge `' + id + '` with nonexistant ' + field + ' `' + val + '`');
          badSourceOrTarget = true;
        }
      }
      if (badSourceOrTarget) {
        removeFromElements();
        continue;
      } // can't create this

      var src = cy.getElementById(_data3.source);
      var tgt = cy.getElementById(_data3.target);

      // only one edge in node if loop
      if (src.same(tgt)) {
        src._private.edges.push(edge);
      } else {
        src._private.edges.push(edge);
        tgt._private.edges.push(edge);
      }
      edge._private.source = src;
      edge._private.target = tgt;
    } // if is edge

    // create mock ids / indexes maps for element so it can be used like collections
    _private.map = new Map$1();
    _private.map.set(id, {
      ele: _ele2,
      index: 0
    });
    _private.removed = false;
    if (addToPool) {
      cy.addToPool(_ele2);
    }
  } // for each element

  // do compound node sanity checks
  for (var _i4 = 0; _i4 < nodes.length; _i4++) {
    // each node
    var node = nodes[_i4];
    var _data4 = node._private.data;
    if (number$1(_data4.parent)) {
      // then automake string
      _data4.parent = '' + _data4.parent;
    }
    var parentId = _data4.parent;
    var specifiedParent = parentId != null;
    if (specifiedParent || node._private.parent) {
      var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);
      if (parent.empty()) {
        // non-existant parent; just remove it
        _data4.parent = undefined;
      } else if (parent[0].removed()) {
        warn('Node added with missing parent, reference to parent removed');
        _data4.parent = undefined;
        node._private.parent = null;
      } else {
        var selfAsParent = false;
        var ancestor = parent;
        while (!ancestor.empty()) {
          if (node.same(ancestor)) {
            // mark self as parent and remove from data
            selfAsParent = true;
            _data4.parent = undefined; // remove parent reference

            // exit or we loop forever
            break;
          }
          ancestor = ancestor.parent();
        }
        if (!selfAsParent) {
          // connect with children
          parent[0]._private.children.push(node);
          node._private.parent = parent[0];

          // let the core know we have a compound graph
          cy_p.hasCompoundNodes = true;
        }
      } // else
    } // if specified parent
  } // for each node

  if (elements.length > 0) {
    var restored = elements.length === self.length ? self : new Collection(cy, elements);
    for (var _i5 = 0; _i5 < restored.length; _i5++) {
      var _ele3 = restored[_i5];
      if (_ele3.isNode()) {
        continue;
      }

      // adding an edge invalidates the traversal caches for the parallel edges
      _ele3.parallelEdges().clearTraversalCache();

      // adding an edge invalidates the traversal cache for the connected nodes
      _ele3.source().clearTraversalCache();
      _ele3.target().clearTraversalCache();
    }
    var toUpdateStyle;
    if (cy_p.hasCompoundNodes) {
      toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());
    } else {
      toUpdateStyle = restored;
    }
    toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);
    if (notifyRenderer) {
      restored.emitAndNotify('add');
    } else if (addToPool) {
      restored.emit('add');
    }
  }
  return self; // chainability
};
elesfn$1.removed = function () {
  var ele = this[0];
  return ele && ele._private.removed;
};
elesfn$1.inside = function () {
  var ele = this[0];
  return ele && !ele._private.removed;
};
elesfn$1.remove = function () {
  var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  var removeFromPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var self = this;
  var elesToRemove = [];
  var elesToRemoveIds = {};
  var cy = self._private.cy;

  // add connected edges
  function addConnectedEdges(node) {
    var edges = node._private.edges;
    for (var i = 0; i < edges.length; i++) {
      add(edges[i]);
    }
  }

  // add descendant nodes
  function addChildren(node) {
    var children = node._private.children;
    for (var i = 0; i < children.length; i++) {
      add(children[i]);
    }
  }
  function add(ele) {
    var alreadyAdded = elesToRemoveIds[ele.id()];
    if (removeFromPool && ele.removed() || alreadyAdded) {
      return;
    } else {
      elesToRemoveIds[ele.id()] = true;
    }
    if (ele.isNode()) {
      elesToRemove.push(ele); // nodes are removed last

      addConnectedEdges(ele);
      addChildren(ele);
    } else {
      elesToRemove.unshift(ele); // edges are removed first
    }
  }

  // make the list of elements to remove
  // (may be removing more than specified due to connected edges etc)

  for (var i = 0, l = self.length; i < l; i++) {
    var ele = self[i];
    add(ele);
  }
  function removeEdgeRef(node, edge) {
    var connectedEdges = node._private.edges;
    removeFromArray(connectedEdges, edge);

    // removing an edges invalidates the traversal cache for its nodes
    node.clearTraversalCache();
  }
  function removeParallelRef(pllEdge) {
    // removing an edge invalidates the traversal caches for the parallel edges
    pllEdge.clearTraversalCache();
  }
  var alteredParents = [];
  alteredParents.ids = {};
  function removeChildRef(parent, ele) {
    ele = ele[0];
    parent = parent[0];
    var children = parent._private.children;
    var pid = parent.id();
    removeFromArray(children, ele); // remove parent => child ref

    ele._private.parent = null; // remove child => parent ref

    if (!alteredParents.ids[pid]) {
      alteredParents.ids[pid] = true;
      alteredParents.push(parent);
    }
  }
  self.dirtyCompoundBoundsCache();
  if (removeFromPool) {
    cy.removeFromPool(elesToRemove); // remove from core pool
  }
  for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {
    var _ele4 = elesToRemove[_i6];
    if (_ele4.isEdge()) {
      // remove references to this edge in its connected nodes
      var src = _ele4.source()[0];
      var tgt = _ele4.target()[0];
      removeEdgeRef(src, _ele4);
      removeEdgeRef(tgt, _ele4);
      var pllEdges = _ele4.parallelEdges();
      for (var j = 0; j < pllEdges.length; j++) {
        var pllEdge = pllEdges[j];
        removeParallelRef(pllEdge);
        if (pllEdge.isBundledBezier()) {
          pllEdge.dirtyBoundingBoxCache();
        }
      }
    } else {
      // remove reference to parent
      var parent = _ele4.parent();
      if (parent.length !== 0) {
        removeChildRef(parent, _ele4);
      }
    }
    if (removeFromPool) {
      // mark as removed
      _ele4._private.removed = true;
    }
  }

  // check to see if we have a compound graph or not
  var elesStillInside = cy._private.elements;
  cy._private.hasCompoundNodes = false;
  for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {
    var _ele5 = elesStillInside[_i7];
    if (_ele5.isParent()) {
      cy._private.hasCompoundNodes = true;
      break;
    }
  }
  var removedElements = new Collection(this.cy(), elesToRemove);
  if (removedElements.size() > 0) {
    // must manually notify since trigger won't do this automatically once removed

    if (notifyRenderer) {
      removedElements.emitAndNotify('remove');
    } else if (removeFromPool) {
      removedElements.emit('remove');
    }
  }

  // the parents who were modified by the removal need their style updated
  for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {
    var _ele6 = alteredParents[_i8];
    if (!removeFromPool || !_ele6.removed()) {
      _ele6.updateStyle();
    }
  }
  return removedElements;
};
elesfn$1.move = function (struct) {
  var cy = this._private.cy;
  var eles = this;

  // just clean up refs, caches, etc. in the same way as when removing and then restoring
  // (our calls to remove/restore do not remove from the graph or make events)
  var notifyRenderer = false;
  var modifyPool = false;
  var toString = function toString(id) {
    return id == null ? id : '' + id;
  }; // id must be string

  if (struct.source !== undefined || struct.target !== undefined) {
    var srcId = toString(struct.source);
    var tgtId = toString(struct.target);
    var srcExists = srcId != null && cy.hasElementWithId(srcId);
    var tgtExists = tgtId != null && cy.hasElementWithId(tgtId);
    if (srcExists || tgtExists) {
      cy.batch(function () {
        // avoid duplicate style updates
        eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
        eles.emitAndNotify('moveout');
        for (var i = 0; i < eles.length; i++) {
          var ele = eles[i];
          var _data5 = ele._private.data;
          if (ele.isEdge()) {
            if (srcExists) {
              _data5.source = srcId;
            }
            if (tgtExists) {
              _data5.target = tgtId;
            }
          }
        }
        eles.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
      });
      eles.emitAndNotify('move');
    }
  } else if (struct.parent !== undefined) {
    // move node to new parent
    var parentId = toString(struct.parent);
    var parentExists = parentId === null || cy.hasElementWithId(parentId);
    if (parentExists) {
      var pidToAssign = parentId === null ? undefined : parentId;
      cy.batch(function () {
        // avoid duplicate style updates
        var updated = eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
        updated.emitAndNotify('moveout');
        for (var i = 0; i < eles.length; i++) {
          var ele = eles[i];
          var _data6 = ele._private.data;
          if (ele.isNode()) {
            _data6.parent = pidToAssign;
          }
        }
        updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
      });
      eles.emitAndNotify('move');
    }
  }
  return this;
};
[elesfn$j, elesfn$i, elesfn$h, elesfn$g, elesfn$f, data, elesfn$d, dimensions, elesfn$9, elesfn$8, elesfn$7, elesfn$6, elesfn$5, elesfn$4, elesfn$3, elesfn$2].forEach(function (props) {
  extend(elesfn$1, props);
});

var corefn$9 = {
  add: function add(opts) {
    var elements;
    var cy = this;

    // add the elements
    if (elementOrCollection(opts)) {
      var eles = opts;
      if (eles._private.cy === cy) {
        // same instance => just restore
        elements = eles.restore();
      } else {
        // otherwise, copy from json
        var jsons = [];
        for (var i = 0; i < eles.length; i++) {
          var ele = eles[i];
          jsons.push(ele.json());
        }
        elements = new Collection(cy, jsons);
      }
    }

    // specify an array of options
    else if (array(opts)) {
      var _jsons = opts;
      elements = new Collection(cy, _jsons);
    }

    // specify via opts.nodes and opts.edges
    else if (plainObject(opts) && (array(opts.nodes) || array(opts.edges))) {
      var elesByGroup = opts;
      var _jsons2 = [];
      var grs = ['nodes', 'edges'];
      for (var _i = 0, il = grs.length; _i < il; _i++) {
        var group = grs[_i];
        var elesArray = elesByGroup[group];
        if (array(elesArray)) {
          for (var j = 0, jl = elesArray.length; j < jl; j++) {
            var json = extend({
              group: group
            }, elesArray[j]);
            _jsons2.push(json);
          }
        }
      }
      elements = new Collection(cy, _jsons2);
    }

    // specify options for one element
    else {
      var _json = opts;
      elements = new Element(cy, _json).collection();
    }
    return elements;
  },
  remove: function remove(collection) {
    if (elementOrCollection(collection)) ; else if (string(collection)) {
      var selector = collection;
      collection = this.$(selector);
    }
    return collection.remove();
  }
};

/* global Float32Array */

/*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
function generateCubicBezier(mX1, mY1, mX2, mY2) {
  var NEWTON_ITERATIONS = 4,
    NEWTON_MIN_SLOPE = 0.001,
    SUBDIVISION_PRECISION = 0.0000001,
    SUBDIVISION_MAX_ITERATIONS = 10,
    kSplineTableSize = 11,
    kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
    float32ArraySupported = typeof Float32Array !== 'undefined';

  /* Must contain four arguments. */
  if (arguments.length !== 4) {
    return false;
  }

  /* Arguments must be numbers. */
  for (var i = 0; i < 4; ++i) {
    if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
      return false;
    }
  }

  /* X values must be in the [0, 1] range. */
  mX1 = Math.min(mX1, 1);
  mX2 = Math.min(mX2, 1);
  mX1 = Math.max(mX1, 0);
  mX2 = Math.max(mX2, 0);
  var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  function A(aA1, aA2) {
    return 1.0 - 3.0 * aA2 + 3.0 * aA1;
  }
  function B(aA1, aA2) {
    return 3.0 * aA2 - 6.0 * aA1;
  }
  function C(aA1) {
    return 3.0 * aA1;
  }
  function calcBezier(aT, aA1, aA2) {
    return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  }
  function getSlope(aT, aA1, aA2) {
    return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  }
  function newtonRaphsonIterate(aX, aGuessT) {
    for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {
      var currentSlope = getSlope(aGuessT, mX1, mX2);
      if (currentSlope === 0.0) {
        return aGuessT;
      }
      var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
      aGuessT -= currentX / currentSlope;
    }
    return aGuessT;
  }
  function calcSampleValues() {
    for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {
      mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);
    }
  }
  function binarySubdivide(aX, aA, aB) {
    var currentX,
      currentT,
      i = 0;
    do {
      currentT = aA + (aB - aA) / 2.0;
      currentX = calcBezier(currentT, mX1, mX2) - aX;
      if (currentX > 0.0) {
        aB = currentT;
      } else {
        aA = currentT;
      }
    } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
    return currentT;
  }
  function getTForX(aX) {
    var intervalStart = 0.0,
      currentSample = 1,
      lastSample = kSplineTableSize - 1;
    for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
      intervalStart += kSampleStepSize;
    }
    --currentSample;
    var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),
      guessForT = intervalStart + dist * kSampleStepSize,
      initialSlope = getSlope(guessForT, mX1, mX2);
    if (initialSlope >= NEWTON_MIN_SLOPE) {
      return newtonRaphsonIterate(aX, guessForT);
    } else if (initialSlope === 0.0) {
      return guessForT;
    } else {
      return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
    }
  }
  var _precomputed = false;
  function precompute() {
    _precomputed = true;
    if (mX1 !== mY1 || mX2 !== mY2) {
      calcSampleValues();
    }
  }
  var f = function f(aX) {
    if (!_precomputed) {
      precompute();
    }
    if (mX1 === mY1 && mX2 === mY2) {
      return aX;
    }
    if (aX === 0) {
      return 0;
    }
    if (aX === 1) {
      return 1;
    }
    return calcBezier(getTForX(aX), mY1, mY2);
  };
  f.getControlPoints = function () {
    return [{
      x: mX1,
      y: mY1
    }, {
      x: mX2,
      y: mY2
    }];
  };
  var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
  f.toString = function () {
    return str;
  };
  return f;
}

/*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
/* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass
   then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
var generateSpringRK4 = function () {
  function springAccelerationForState(state) {
    return -state.tension * state.x - state.friction * state.v;
  }
  function springEvaluateStateWithDerivative(initialState, dt, derivative) {
    var state = {
      x: initialState.x + derivative.dx * dt,
      v: initialState.v + derivative.dv * dt,
      tension: initialState.tension,
      friction: initialState.friction
    };
    return {
      dx: state.v,
      dv: springAccelerationForState(state)
    };
  }
  function springIntegrateState(state, dt) {
    var a = {
        dx: state.v,
        dv: springAccelerationForState(state)
      },
      b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
      c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
      d = springEvaluateStateWithDerivative(state, dt, c),
      dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
      dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
    state.x = state.x + dxdt * dt;
    state.v = state.v + dvdt * dt;
    return state;
  }
  return function springRK4Factory(tension, friction, duration) {
    var initState = {
        x: -1,
        v: 0,
        tension: null,
        friction: null
      },
      path = [0],
      time_lapsed = 0,
      tolerance = 1 / 10000,
      DT = 16 / 1000,
      have_duration,
      dt,
      last_state;
    tension = parseFloat(tension) || 500;
    friction = parseFloat(friction) || 20;
    duration = duration || null;
    initState.tension = tension;
    initState.friction = friction;
    have_duration = duration !== null;

    /* Calculate the actual time it takes for this animation to complete with the provided conditions. */
    if (have_duration) {
      /* Run the simulation without a duration. */
      time_lapsed = springRK4Factory(tension, friction);
      /* Compute the adjusted time delta. */
      dt = time_lapsed / duration * DT;
    } else {
      dt = DT;
    }
    for (;;) {
      /* Next/step function .*/
      last_state = springIntegrateState(last_state || initState, dt);
      /* Store the position. */
      path.push(1 + last_state.x);
      time_lapsed += 16;
      /* If the change threshold is reached, break. */
      if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
        break;
      }
    }

    /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
       computed path and returns a snapshot of the position according to a given percentComplete. */
    return !have_duration ? time_lapsed : function (percentComplete) {
      return path[percentComplete * (path.length - 1) | 0];
    };
  };
}();

var cubicBezier = function cubicBezier(t1, p1, t2, p2) {
  var bezier = generateCubicBezier(t1, p1, t2, p2);
  return function (start, end, percent) {
    return start + (end - start) * bezier(percent);
  };
};
var easings = {
  'linear': function linear(start, end, percent) {
    return start + (end - start) * percent;
  },
  // default easings
  'ease': cubicBezier(0.25, 0.1, 0.25, 1),
  'ease-in': cubicBezier(0.42, 0, 1, 1),
  'ease-out': cubicBezier(0, 0, 0.58, 1),
  'ease-in-out': cubicBezier(0.42, 0, 0.58, 1),
  // sine
  'ease-in-sine': cubicBezier(0.47, 0, 0.745, 0.715),
  'ease-out-sine': cubicBezier(0.39, 0.575, 0.565, 1),
  'ease-in-out-sine': cubicBezier(0.445, 0.05, 0.55, 0.95),
  // quad
  'ease-in-quad': cubicBezier(0.55, 0.085, 0.68, 0.53),
  'ease-out-quad': cubicBezier(0.25, 0.46, 0.45, 0.94),
  'ease-in-out-quad': cubicBezier(0.455, 0.03, 0.515, 0.955),
  // cubic
  'ease-in-cubic': cubicBezier(0.55, 0.055, 0.675, 0.19),
  'ease-out-cubic': cubicBezier(0.215, 0.61, 0.355, 1),
  'ease-in-out-cubic': cubicBezier(0.645, 0.045, 0.355, 1),
  // quart
  'ease-in-quart': cubicBezier(0.895, 0.03, 0.685, 0.22),
  'ease-out-quart': cubicBezier(0.165, 0.84, 0.44, 1),
  'ease-in-out-quart': cubicBezier(0.77, 0, 0.175, 1),
  // quint
  'ease-in-quint': cubicBezier(0.755, 0.05, 0.855, 0.06),
  'ease-out-quint': cubicBezier(0.23, 1, 0.32, 1),
  'ease-in-out-quint': cubicBezier(0.86, 0, 0.07, 1),
  // expo
  'ease-in-expo': cubicBezier(0.95, 0.05, 0.795, 0.035),
  'ease-out-expo': cubicBezier(0.19, 1, 0.22, 1),
  'ease-in-out-expo': cubicBezier(1, 0, 0, 1),
  // circ
  'ease-in-circ': cubicBezier(0.6, 0.04, 0.98, 0.335),
  'ease-out-circ': cubicBezier(0.075, 0.82, 0.165, 1),
  'ease-in-out-circ': cubicBezier(0.785, 0.135, 0.15, 0.86),
  // user param easings...

  'spring': function spring(tension, friction, duration) {
    if (duration === 0) {
      // can't get a spring w/ duration 0
      return easings.linear; // duration 0 => jump to end so impl doesn't matter
    }
    var spring = generateSpringRK4(tension, friction, duration);
    return function (start, end, percent) {
      return start + (end - start) * spring(percent);
    };
  },
  'cubic-bezier': cubicBezier
};

function getEasedValue(type, start, end, percent, easingFn) {
  if (percent === 1) {
    return end;
  }
  if (start === end) {
    return end;
  }
  var val = easingFn(start, end, percent);
  if (type == null) {
    return val;
  }
  if (type.roundValue || type.color) {
    val = Math.round(val);
  }
  if (type.min !== undefined) {
    val = Math.max(val, type.min);
  }
  if (type.max !== undefined) {
    val = Math.min(val, type.max);
  }
  return val;
}
function getValue(prop, spec) {
  if (prop.pfValue != null || prop.value != null) {
    if (prop.pfValue != null && (spec == null || spec.type.units !== '%')) {
      return prop.pfValue;
    } else {
      return prop.value;
    }
  } else {
    return prop;
  }
}
function ease(startProp, endProp, percent, easingFn, propSpec) {
  var type = propSpec != null ? propSpec.type : null;
  if (percent < 0) {
    percent = 0;
  } else if (percent > 1) {
    percent = 1;
  }
  var start = getValue(startProp, propSpec);
  var end = getValue(endProp, propSpec);
  if (number$1(start) && number$1(end)) {
    return getEasedValue(type, start, end, percent, easingFn);
  } else if (array(start) && array(end)) {
    var easedArr = [];
    for (var i = 0; i < end.length; i++) {
      var si = start[i];
      var ei = end[i];
      if (si != null && ei != null) {
        var val = getEasedValue(type, si, ei, percent, easingFn);
        easedArr.push(val);
      } else {
        easedArr.push(ei);
      }
    }
    return easedArr;
  }
  return undefined;
}

function step$1(self, ani, now, isCore) {
  var isEles = !isCore;
  var _p = self._private;
  var ani_p = ani._private;
  var pEasing = ani_p.easing;
  var startTime = ani_p.startTime;
  var cy = isCore ? self : self.cy();
  var style = cy.style();
  if (!ani_p.easingImpl) {
    if (pEasing == null) {
      // use default
      ani_p.easingImpl = easings['linear'];
    } else {
      // then define w/ name
      var easingVals;
      if (string(pEasing)) {
        var easingProp = style.parse('transition-timing-function', pEasing);
        easingVals = easingProp.value;
      } else {
        // then assume preparsed array
        easingVals = pEasing;
      }
      var name, args;
      if (string(easingVals)) {
        name = easingVals;
        args = [];
      } else {
        name = easingVals[1];
        args = easingVals.slice(2).map(function (n) {
          return +n;
        });
      }
      if (args.length > 0) {
        // create with args
        if (name === 'spring') {
          args.push(ani_p.duration); // need duration to generate spring
        }
        ani_p.easingImpl = easings[name].apply(null, args);
      } else {
        // static impl by name
        ani_p.easingImpl = easings[name];
      }
    }
  }
  var easing = ani_p.easingImpl;
  var percent;
  if (ani_p.duration === 0) {
    percent = 1;
  } else {
    percent = (now - startTime) / ani_p.duration;
  }
  if (ani_p.applying) {
    percent = ani_p.progress;
  }
  if (percent < 0) {
    percent = 0;
  } else if (percent > 1) {
    percent = 1;
  }
  if (ani_p.delay == null) {
    // then update

    var startPos = ani_p.startPosition;
    var endPos = ani_p.position;
    if (endPos && isEles && !self.locked()) {
      var newPos = {};
      if (valid(startPos.x, endPos.x)) {
        newPos.x = ease(startPos.x, endPos.x, percent, easing);
      }
      if (valid(startPos.y, endPos.y)) {
        newPos.y = ease(startPos.y, endPos.y, percent, easing);
      }
      self.position(newPos);
    }
    var startPan = ani_p.startPan;
    var endPan = ani_p.pan;
    var pan = _p.pan;
    var animatingPan = endPan != null && isCore;
    if (animatingPan) {
      if (valid(startPan.x, endPan.x)) {
        pan.x = ease(startPan.x, endPan.x, percent, easing);
      }
      if (valid(startPan.y, endPan.y)) {
        pan.y = ease(startPan.y, endPan.y, percent, easing);
      }
      self.emit('pan');
    }
    var startZoom = ani_p.startZoom;
    var endZoom = ani_p.zoom;
    var animatingZoom = endZoom != null && isCore;
    if (animatingZoom) {
      if (valid(startZoom, endZoom)) {
        _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);
      }
      self.emit('zoom');
    }
    if (animatingPan || animatingZoom) {
      self.emit('viewport');
    }
    var props = ani_p.style;
    if (props && props.length > 0 && isEles) {
      for (var i = 0; i < props.length; i++) {
        var prop = props[i];
        var _name = prop.name;
        var end = prop;
        var start = ani_p.startStyle[_name];
        var propSpec = style.properties[start.name];
        var easedVal = ease(start, end, percent, easing, propSpec);
        style.overrideBypass(self, _name, easedVal);
      } // for props

      self.emit('style');
    } // if
  }
  ani_p.progress = percent;
  return percent;
}
function valid(start, end) {
  if (start == null || end == null) {
    return false;
  }
  if (number$1(start) && number$1(end)) {
    return true;
  } else if (start && end) {
    return true;
  }
  return false;
}

function startAnimation(self, ani, now, isCore) {
  var ani_p = ani._private;
  ani_p.started = true;
  ani_p.startTime = now - ani_p.progress * ani_p.duration;
}

function stepAll(now, cy) {
  var eles = cy._private.aniEles;
  var doneEles = [];
  function stepOne(ele, isCore) {
    var _p = ele._private;
    var current = _p.animation.current;
    var queue = _p.animation.queue;
    var ranAnis = false;

    // if nothing currently animating, get something from the queue
    if (current.length === 0) {
      var next = queue.shift();
      if (next) {
        current.push(next);
      }
    }
    var callbacks = function callbacks(_callbacks) {
      for (var j = _callbacks.length - 1; j >= 0; j--) {
        var cb = _callbacks[j];
        cb();
      }
      _callbacks.splice(0, _callbacks.length);
    };

    // step and remove if done
    for (var i = current.length - 1; i >= 0; i--) {
      var ani = current[i];
      var ani_p = ani._private;
      if (ani_p.stopped) {
        current.splice(i, 1);
        ani_p.hooked = false;
        ani_p.playing = false;
        ani_p.started = false;
        callbacks(ani_p.frames);
        continue;
      }
      if (!ani_p.playing && !ani_p.applying) {
        continue;
      }

      // an apply() while playing shouldn't do anything
      if (ani_p.playing && ani_p.applying) {
        ani_p.applying = false;
      }
      if (!ani_p.started) {
        startAnimation(ele, ani, now);
      }
      step$1(ele, ani, now, isCore);
      if (ani_p.applying) {
        ani_p.applying = false;
      }
      callbacks(ani_p.frames);
      if (ani_p.step != null) {
        ani_p.step(now);
      }
      if (ani.completed()) {
        current.splice(i, 1);
        ani_p.hooked = false;
        ani_p.playing = false;
        ani_p.started = false;
        callbacks(ani_p.completes);
      }
      ranAnis = true;
    }
    if (!isCore && current.length === 0 && queue.length === 0) {
      doneEles.push(ele);
    }
    return ranAnis;
  } // stepElement

  // handle all eles
  var ranEleAni = false;
  for (var e = 0; e < eles.length; e++) {
    var ele = eles[e];
    var handledThisEle = stepOne(ele);
    ranEleAni = ranEleAni || handledThisEle;
  } // each element

  var ranCoreAni = stepOne(cy, true);

  // notify renderer
  if (ranEleAni || ranCoreAni) {
    if (eles.length > 0) {
      cy.notify('draw', eles);
    } else {
      cy.notify('draw');
    }
  }

  // remove elements from list of currently animating if its queues are empty
  eles.unmerge(doneEles);
  cy.emit('step');
} // stepAll

var corefn$8 = {
  // pull in animation functions
  animate: define.animate(),
  animation: define.animation(),
  animated: define.animated(),
  clearQueue: define.clearQueue(),
  delay: define.delay(),
  delayAnimation: define.delayAnimation(),
  stop: define.stop(),
  addToAnimationPool: function addToAnimationPool(eles) {
    var cy = this;
    if (!cy.styleEnabled()) {
      return;
    } // save cycles when no style used

    cy._private.aniEles.merge(eles);
  },
  stopAnimationLoop: function stopAnimationLoop() {
    this._private.animationsRunning = false;
  },
  startAnimationLoop: function startAnimationLoop() {
    var cy = this;
    cy._private.animationsRunning = true;
    if (!cy.styleEnabled()) {
      return;
    } // save cycles when no style used

    // NB the animation loop will exec in headless environments if style enabled
    // and explicit cy.destroy() is necessary to stop the loop

    function headlessStep() {
      if (!cy._private.animationsRunning) {
        return;
      }
      requestAnimationFrame(function animationStep(now) {
        stepAll(now, cy);
        headlessStep();
      });
    }
    var renderer = cy.renderer();
    if (renderer && renderer.beforeRender) {
      // let the renderer schedule animations
      renderer.beforeRender(function rendererAnimationStep(willDraw, now) {
        stepAll(now, cy);
      }, renderer.beforeRenderPriorities.animations);
    } else {
      // manage the animation loop ourselves
      headlessStep(); // first call
    }
  }
};

var emitterOptions = {
  qualifierCompare: function qualifierCompare(selector1, selector2) {
    if (selector1 == null || selector2 == null) {
      return selector1 == null && selector2 == null;
    } else {
      return selector1.sameText(selector2);
    }
  },
  eventMatches: function eventMatches(cy, listener, eventObj) {
    var selector = listener.qualifier;
    if (selector != null) {
      return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
    }
    return true;
  },
  addEventFields: function addEventFields(cy, evt) {
    evt.cy = cy;
    evt.target = cy;
  },
  callbackContext: function callbackContext(cy, listener, eventObj) {
    return listener.qualifier != null ? eventObj.target : cy;
  }
};
var argSelector = function argSelector(arg) {
  if (string(arg)) {
    return new Selector(arg);
  } else {
    return arg;
  }
};
var elesfn = {
  createEmitter: function createEmitter() {
    var _p = this._private;
    if (!_p.emitter) {
      _p.emitter = new Emitter(emitterOptions, this);
    }
    return this;
  },
  emitter: function emitter() {
    return this._private.emitter;
  },
  on: function on(events, selector, callback) {
    this.emitter().on(events, argSelector(selector), callback);
    return this;
  },
  removeListener: function removeListener(events, selector, callback) {
    this.emitter().removeListener(events, argSelector(selector), callback);
    return this;
  },
  removeAllListeners: function removeAllListeners() {
    this.emitter().removeAllListeners();
    return this;
  },
  one: function one(events, selector, callback) {
    this.emitter().one(events, argSelector(selector), callback);
    return this;
  },
  once: function once(events, selector, callback) {
    this.emitter().one(events, argSelector(selector), callback);
    return this;
  },
  emit: function emit(events, extraParams) {
    this.emitter().emit(events, extraParams);
    return this;
  },
  emitAndNotify: function emitAndNotify(event, eles) {
    this.emit(event);
    this.notify(event, eles);
    return this;
  }
};
define.eventAliasesOn(elesfn);

var corefn$7 = {
  png: function png(options) {
    var renderer = this._private.renderer;
    options = options || {};
    return renderer.png(options);
  },
  jpg: function jpg(options) {
    var renderer = this._private.renderer;
    options = options || {};
    options.bg = options.bg || '#fff';
    return renderer.jpg(options);
  }
};
corefn$7.jpeg = corefn$7.jpg;

var corefn$6 = {
  layout: function layout(options) {
    var cy = this;
    if (options == null) {
      error('Layout options must be specified to make a layout');
      return;
    }
    if (options.name == null) {
      error('A `name` must be specified to make a layout');
      return;
    }
    var name = options.name;
    var Layout = cy.extension('layout', name);
    if (Layout == null) {
      error('No such layout `' + name + '` found.  Did you forget to import it and `cytoscape.use()` it?');
      return;
    }
    var eles;
    if (string(options.eles)) {
      eles = cy.$(options.eles);
    } else {
      eles = options.eles != null ? options.eles : cy.$();
    }
    var layout = new Layout(extend({}, options, {
      cy: cy,
      eles: eles
    }));
    return layout;
  }
};
corefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;

var corefn$5 = {
  notify: function notify(eventName, eventEles) {
    var _p = this._private;
    if (this.batching()) {
      _p.batchNotifications = _p.batchNotifications || {};
      var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();
      if (eventEles != null) {
        eles.merge(eventEles);
      }
      return; // notifications are disabled during batching
    }
    if (!_p.notificationsEnabled) {
      return;
    } // exit on disabled

    var renderer = this.renderer();

    // exit if destroy() called on core or renderer in between frames #1499 #1528
    if (this.destroyed() || !renderer) {
      return;
    }
    renderer.notify(eventName, eventEles);
  },
  notifications: function notifications(bool) {
    var p = this._private;
    if (bool === undefined) {
      return p.notificationsEnabled;
    } else {
      p.notificationsEnabled = bool ? true : false;
    }
    return this;
  },
  noNotifications: function noNotifications(callback) {
    this.notifications(false);
    callback();
    this.notifications(true);
  },
  batching: function batching() {
    return this._private.batchCount > 0;
  },
  startBatch: function startBatch() {
    var _p = this._private;
    if (_p.batchCount == null) {
      _p.batchCount = 0;
    }
    if (_p.batchCount === 0) {
      _p.batchStyleEles = this.collection();
      _p.batchNotifications = {};
    }
    _p.batchCount++;
    return this;
  },
  endBatch: function endBatch() {
    var _p = this._private;
    if (_p.batchCount === 0) {
      return this;
    }
    _p.batchCount--;
    if (_p.batchCount === 0) {
      // update style for dirty eles
      _p.batchStyleEles.updateStyle();
      var renderer = this.renderer();

      // notify the renderer of queued eles and event types
      Object.keys(_p.batchNotifications).forEach(function (eventName) {
        var eles = _p.batchNotifications[eventName];
        if (eles.empty()) {
          renderer.notify(eventName);
        } else {
          renderer.notify(eventName, eles);
        }
      });
    }
    return this;
  },
  batch: function batch(callback) {
    this.startBatch();
    callback();
    this.endBatch();
    return this;
  },
  // for backwards compatibility
  batchData: function batchData(map) {
    var cy = this;
    return this.batch(function () {
      var ids = Object.keys(map);
      for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var data = map[id];
        var ele = cy.getElementById(id);
        ele.data(data);
      }
    });
  }
};

var rendererDefaults = defaults$g({
  hideEdgesOnViewport: false,
  textureOnViewport: false,
  motionBlur: false,
  motionBlurOpacity: 0.05,
  pixelRatio: undefined,
  desktopTapThreshold: 4,
  touchTapThreshold: 8,
  wheelSensitivity: 1,
  debug: false,
  showFps: false,
  // webgl options
  webgl: false,
  webglDebug: false,
  webglDebugShowAtlases: false,
  // defaults good for mobile
  webglTexSize: 2048,
  webglTexRows: 36,
  webglTexRowsNodes: 18,
  webglBatchSize: 2048,
  webglTexPerBatch: 14,
  webglBgColor: [255, 255, 255]
});
var corefn$4 = {
  renderTo: function renderTo(context, zoom, pan, pxRatio) {
    var r = this._private.renderer;
    r.renderTo(context, zoom, pan, pxRatio);
    return this;
  },
  renderer: function renderer() {
    return this._private.renderer;
  },
  forceRender: function forceRender() {
    this.notify('draw');
    return this;
  },
  resize: function resize() {
    this.invalidateSize();
    this.emitAndNotify('resize');
    return this;
  },
  initRenderer: function initRenderer(options) {
    var cy = this;
    var RendererProto = cy.extension('renderer', options.name);
    if (RendererProto == null) {
      error("Can not initialise: No such renderer `".concat(options.name, "` found. Did you forget to import it and `cytoscape.use()` it?"));
      return;
    }
    if (options.wheelSensitivity !== undefined) {
      warn("You have set a custom wheel sensitivity.  This will make your app zoom unnaturally when using mainstream mice.  You should change this value from the default only if you can guarantee that all your users will use the same hardware and OS configuration as your current machine.");
    }
    var rOpts = rendererDefaults(options);
    rOpts.cy = cy;
    cy._private.renderer = new RendererProto(rOpts);
    this.notify('init');
  },
  destroyRenderer: function destroyRenderer() {
    var cy = this;
    cy.notify('destroy'); // destroy the renderer

    var domEle = cy.container();
    if (domEle) {
      domEle._cyreg = null;
      while (domEle.childNodes.length > 0) {
        domEle.removeChild(domEle.childNodes[0]);
      }
    }
    cy._private.renderer = null; // to be extra safe, remove the ref
    cy.mutableElements().forEach(function (ele) {
      var _p = ele._private;
      _p.rscratch = {};
      _p.rstyle = {};
      _p.animation.current = [];
      _p.animation.queue = [];
    });
  },
  onRender: function onRender(fn) {
    return this.on('render', fn);
  },
  offRender: function offRender(fn) {
    return this.off('render', fn);
  }
};
corefn$4.invalidateDimensions = corefn$4.resize;

var corefn$3 = {
  // get a collection
  // - empty collection on no args
  // - collection of elements in the graph on selector arg
  // - guarantee a returned collection when elements or collection specified
  collection: function collection(eles, opts) {
    if (string(eles)) {
      return this.$(eles);
    } else if (elementOrCollection(eles)) {
      return eles.collection();
    } else if (array(eles)) {
      if (!opts) {
        opts = {};
      }
      return new Collection(this, eles, opts.unique, opts.removed);
    }
    return new Collection(this);
  },
  nodes: function nodes(selector) {
    var nodes = this.$(function (ele) {
      return ele.isNode();
    });
    if (selector) {
      return nodes.filter(selector);
    }
    return nodes;
  },
  edges: function edges(selector) {
    var edges = this.$(function (ele) {
      return ele.isEdge();
    });
    if (selector) {
      return edges.filter(selector);
    }
    return edges;
  },
  // search the graph like jQuery
  $: function $(selector) {
    var eles = this._private.elements;
    if (selector) {
      return eles.filter(selector);
    } else {
      return eles.spawnSelf();
    }
  },
  mutableElements: function mutableElements() {
    return this._private.elements;
  }
};

// aliases
corefn$3.elements = corefn$3.filter = corefn$3.$;

var styfn$8 = {};

// keys for style blocks, e.g. ttfftt
var TRUE = 't';
var FALSE = 'f';

// (potentially expensive calculation)
// apply the style to the element based on
// - its bypass
// - what selectors match it
styfn$8.apply = function (eles) {
  var self = this;
  var _p = self._private;
  var cy = _p.cy;
  var updatedEles = cy.collection();
  for (var ie = 0; ie < eles.length; ie++) {
    var ele = eles[ie];
    var cxtMeta = self.getContextMeta(ele);
    if (cxtMeta.empty) {
      continue;
    }
    var cxtStyle = self.getContextStyle(cxtMeta);
    var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);
    if (ele._private.appliedInitStyle) {
      self.updateTransitions(ele, app.diffProps);
    } else {
      ele._private.appliedInitStyle = true;
    }
    var hintsDiff = self.updateStyleHints(ele);
    if (hintsDiff) {
      updatedEles.push(ele);
    }
  } // for elements

  return updatedEles;
};
styfn$8.getPropertiesDiff = function (oldCxtKey, newCxtKey) {
  var self = this;
  var cache = self._private.propDiffs = self._private.propDiffs || {};
  var dualCxtKey = oldCxtKey + '-' + newCxtKey;
  var cachedVal = cache[dualCxtKey];
  if (cachedVal) {
    return cachedVal;
  }
  var diffProps = [];
  var addedProp = {};
  for (var i = 0; i < self.length; i++) {
    var cxt = self[i];
    var oldHasCxt = oldCxtKey[i] === TRUE;
    var newHasCxt = newCxtKey[i] === TRUE;
    var cxtHasDiffed = oldHasCxt !== newHasCxt;
    var cxtHasMappedProps = cxt.mappedProperties.length > 0;
    if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {
      var props = undefined;
      if (cxtHasDiffed && cxtHasMappedProps) {
        props = cxt.properties; // suffices b/c mappedProperties is a subset of properties
      } else if (cxtHasDiffed) {
        props = cxt.properties; // need to check them all
      } else if (cxtHasMappedProps) {
        props = cxt.mappedProperties; // only need to check mapped
      }
      for (var j = 0; j < props.length; j++) {
        var prop = props[j];
        var name = prop.name;

        // if a later context overrides this property, then the fact that this context has switched/diffed doesn't matter
        // (semi expensive check since it makes this function O(n^2) on context length, but worth it since overall result
        // is cached)
        var laterCxtOverrides = false;
        for (var k = i + 1; k < self.length; k++) {
          var laterCxt = self[k];
          var hasLaterCxt = newCxtKey[k] === TRUE;
          if (!hasLaterCxt) {
            continue;
          } // can't override unless the context is active

          laterCxtOverrides = laterCxt.properties[prop.name] != null;
          if (laterCxtOverrides) {
            break;
          } // exit early as long as one later context overrides
        }
        if (!addedProp[name] && !laterCxtOverrides) {
          addedProp[name] = true;
          diffProps.push(name);
        }
      } // for props
    } // if
  } // for contexts

  cache[dualCxtKey] = diffProps;
  return diffProps;
};
styfn$8.getContextMeta = function (ele) {
  var self = this;
  var cxtKey = '';
  var diffProps;
  var prevKey = ele._private.styleCxtKey || '';

  // get the cxt key
  for (var i = 0; i < self.length; i++) {
    var context = self[i];
    var contextSelectorMatches = context.selector && context.selector.matches(ele); // NB: context.selector may be null for 'core'

    if (contextSelectorMatches) {
      cxtKey += TRUE;
    } else {
      cxtKey += FALSE;
    }
  } // for context

  diffProps = self.getPropertiesDiff(prevKey, cxtKey);
  ele._private.styleCxtKey = cxtKey;
  return {
    key: cxtKey,
    diffPropNames: diffProps,
    empty: diffProps.length === 0
  };
};

// gets a computed ele style object based on matched contexts
styfn$8.getContextStyle = function (cxtMeta) {
  var cxtKey = cxtMeta.key;
  var self = this;
  var cxtStyles = this._private.contextStyles = this._private.contextStyles || {};

  // if already computed style, returned cached copy
  if (cxtStyles[cxtKey]) {
    return cxtStyles[cxtKey];
  }
  var style = {
    _private: {
      key: cxtKey
    }
  };
  for (var i = 0; i < self.length; i++) {
    var cxt = self[i];
    var hasCxt = cxtKey[i] === TRUE;
    if (!hasCxt) {
      continue;
    }
    for (var j = 0; j < cxt.properties.length; j++) {
      var prop = cxt.properties[j];
      style[prop.name] = prop;
    }
  }
  cxtStyles[cxtKey] = style;
  return style;
};
styfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {
  var self = this;
  var diffProps = cxtMeta.diffPropNames;
  var retDiffProps = {};
  var types = self.types;
  for (var i = 0; i < diffProps.length; i++) {
    var diffPropName = diffProps[i];
    var cxtProp = cxtStyle[diffPropName];
    var eleProp = ele.pstyle(diffPropName);
    if (!cxtProp) {
      // no context prop means delete
      if (!eleProp) {
        continue; // no existing prop means nothing needs to be removed
        // nb affects initial application on mapped values like control-point-distances
      } else if (eleProp.bypass) {
        cxtProp = {
          name: diffPropName,
          deleteBypassed: true
        };
      } else {
        cxtProp = {
          name: diffPropName,
          "delete": true
        };
      }
    }

    // save cycles when the context prop doesn't need to be applied
    if (eleProp === cxtProp) {
      continue;
    }

    // save cycles when a mapped context prop doesn't need to be applied
    if (cxtProp.mapped === types.fn // context prop is function mapper
    && eleProp != null // some props can be null even by default (e.g. a prop that overrides another one)
    && eleProp.mapping != null // ele prop is a concrete value from from a mapper
    && eleProp.mapping.value === cxtProp.value // the current prop on the ele is a flat prop value for the function mapper
    ) {
      // NB don't write to cxtProp, as it's shared among eles (stored in stylesheet)
      var mapping = eleProp.mapping; // can write to mapping, as it's a per-ele copy
      var fnValue = mapping.fnValue = cxtProp.value(ele); // temporarily cache the value in case of a miss

      if (fnValue === mapping.prevFnValue) {
        continue;
      }
    }
    var retDiffProp = retDiffProps[diffPropName] = {
      prev: eleProp
    };
    self.applyParsedProperty(ele, cxtProp);
    retDiffProp.next = ele.pstyle(diffPropName);
    if (retDiffProp.next && retDiffProp.next.bypass) {
      retDiffProp.next = retDiffProp.next.bypassed;
    }
  }
  return {
    diffProps: retDiffProps
  };
};
styfn$8.updateStyleHints = function (ele) {
  var _p = ele._private;
  var self = this;
  var propNames = self.propertyGroupNames;
  var propGrKeys = self.propertyGroupKeys;
  var propHash = function propHash(ele, propNames, seedKey) {
    return self.getPropertiesHash(ele, propNames, seedKey);
  };
  var oldStyleKey = _p.styleKey;
  if (ele.removed()) {
    return false;
  }
  var isNode = _p.group === 'nodes';

  // get the style key hashes per prop group
  // but lazily -- only use non-default prop values to reduce the number of hashes
  //

  var overriddenStyles = ele._private.style;
  propNames = Object.keys(overriddenStyles);
  for (var i = 0; i < propGrKeys.length; i++) {
    var grKey = propGrKeys[i];
    _p.styleKeys[grKey] = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  }
  var updateGrKey1 = function updateGrKey1(val, grKey) {
    return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);
  };
  var updateGrKey2 = function updateGrKey2(val, grKey) {
    return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);
  };
  var updateGrKey = function updateGrKey(val, grKey) {
    updateGrKey1(val, grKey);
    updateGrKey2(val, grKey);
  };
  var updateGrKeyWStr = function updateGrKeyWStr(strVal, grKey) {
    for (var j = 0; j < strVal.length; j++) {
      var ch = strVal.charCodeAt(j);
      updateGrKey1(ch, grKey);
      updateGrKey2(ch, grKey);
    }
  };

  // - hashing works on 32 bit ints b/c we use bitwise ops
  // - small numbers get cut off (e.g. 0.123 is seen as 0 by the hashing function)
  // - raise up small numbers so more significant digits are seen by hashing
  // - make small numbers larger than a normal value to avoid collisions
  // - works in practice and it's relatively cheap
  var N = 2000000000;
  var cleanNum = function cleanNum(val) {
    return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;
  };
  for (var _i = 0; _i < propNames.length; _i++) {
    var name = propNames[_i];
    var parsedProp = overriddenStyles[name];
    if (parsedProp == null) {
      continue;
    }
    var propInfo = this.properties[name];
    var type = propInfo.type;
    var _grKey = propInfo.groupKey;
    var normalizedNumberVal = undefined;
    if (propInfo.hashOverride != null) {
      normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);
    } else if (parsedProp.pfValue != null) {
      normalizedNumberVal = parsedProp.pfValue;
    }

    // might not be a number if it allows enums
    var numberVal = propInfo.enums == null ? parsedProp.value : null;
    var haveNormNum = normalizedNumberVal != null;
    var haveUnitedNum = numberVal != null;
    var haveNum = haveNormNum || haveUnitedNum;
    var units = parsedProp.units;

    // numbers are cheaper to hash than strings
    // 1 hash op vs n hash ops (for length n string)
    if (type.number && haveNum && !type.multiple) {
      var v = haveNormNum ? normalizedNumberVal : numberVal;
      updateGrKey(cleanNum(v), _grKey);
      if (!haveNormNum && units != null) {
        updateGrKeyWStr(units, _grKey);
      }
    } else {
      updateGrKeyWStr(parsedProp.strValue, _grKey);
    }
  }

  // overall style key
  //

  var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  for (var _i2 = 0; _i2 < propGrKeys.length; _i2++) {
    var _grKey2 = propGrKeys[_i2];
    var grHash = _p.styleKeys[_grKey2];
    hash[0] = hashInt(grHash[0], hash[0]);
    hash[1] = hashIntAlt(grHash[1], hash[1]);
  }
  _p.styleKey = combineHashes(hash[0], hash[1]);

  // label dims
  //

  var sk = _p.styleKeys;
  _p.labelDimsKey = combineHashesArray(sk.labelDimensions);
  var labelKeys = propHash(ele, ['label'], sk.labelDimensions);
  _p.labelKey = combineHashesArray(labelKeys);
  _p.labelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, labelKeys));
  if (!isNode) {
    var sourceLabelKeys = propHash(ele, ['source-label'], sk.labelDimensions);
    _p.sourceLabelKey = combineHashesArray(sourceLabelKeys);
    _p.sourceLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, sourceLabelKeys));
    var targetLabelKeys = propHash(ele, ['target-label'], sk.labelDimensions);
    _p.targetLabelKey = combineHashesArray(targetLabelKeys);
    _p.targetLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, targetLabelKeys));
  }

  // node
  //

  if (isNode) {
    var _p$styleKeys = _p.styleKeys,
      nodeBody = _p$styleKeys.nodeBody,
      nodeBorder = _p$styleKeys.nodeBorder,
      nodeOutline = _p$styleKeys.nodeOutline,
      backgroundImage = _p$styleKeys.backgroundImage,
      compound = _p$styleKeys.compound,
      pie = _p$styleKeys.pie,
      stripe = _p$styleKeys.stripe;
    var nodeKeys = [nodeBody, nodeBorder, nodeOutline, backgroundImage, compound, pie, stripe].filter(function (k) {
      return k != null;
    }).reduce(hashArrays, [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT]);
    _p.nodeKey = combineHashesArray(nodeKeys);
    _p.hasPie = pie != null && pie[0] !== DEFAULT_HASH_SEED && pie[1] !== DEFAULT_HASH_SEED_ALT;
    _p.hasStripe = stripe != null && stripe[0] !== DEFAULT_HASH_SEED && stripe[1] !== DEFAULT_HASH_SEED_ALT;
  }
  return oldStyleKey !== _p.styleKey;
};
styfn$8.clearStyleHints = function (ele) {
  var _p = ele._private;
  _p.styleCxtKey = '';
  _p.styleKeys = {};
  _p.styleKey = null;
  _p.labelKey = null;
  _p.labelStyleKey = null;
  _p.sourceLabelKey = null;
  _p.sourceLabelStyleKey = null;
  _p.targetLabelKey = null;
  _p.targetLabelStyleKey = null;
  _p.nodeKey = null;
  _p.hasPie = null;
  _p.hasStripe = null;
};

// apply a property to the style (for internal use)
// returns whether application was successful
//
// now, this function flattens the property, and here's how:
//
// for parsedProp:{ bypass: true, deleteBypass: true }
// no property is generated, instead the bypass property in the
// element's style is replaced by what's pointed to by the `bypassed`
// field in the bypass property (i.e. restoring the property the
// bypass was overriding)
//
// for parsedProp:{ mapped: truthy }
// the generated flattenedProp:{ mapping: prop }
//
// for parsedProp:{ bypass: true }
// the generated flattenedProp:{ bypassed: parsedProp }
styfn$8.applyParsedProperty = function (ele, parsedProp) {
  var self = this;
  var prop = parsedProp;
  var style = ele._private.style;
  var flatProp;
  var types = self.types;
  var type = self.properties[prop.name].type;
  var propIsBypass = prop.bypass;
  var origProp = style[prop.name];
  var origPropIsBypass = origProp && origProp.bypass;
  var _p = ele._private;
  var flatPropMapping = 'mapping';
  var getVal = function getVal(p) {
    if (p == null) {
      return null;
    } else if (p.pfValue != null) {
      return p.pfValue;
    } else {
      return p.value;
    }
  };
  var checkTriggers = function checkTriggers() {
    var fromVal = getVal(origProp);
    var toVal = getVal(prop);
    self.checkTriggers(ele, prop.name, fromVal, toVal);
  };

  // edge sanity checks to prevent the client from making serious mistakes
  if (parsedProp.name === 'curve-style' && ele.isEdge() && (
  // loops must be bundled beziers
  parsedProp.value !== 'bezier' && ele.isLoop() ||
  // edges connected to compound nodes can not be haystacks
  parsedProp.value === 'haystack' && (ele.source().isParent() || ele.target().isParent()))) {
    prop = parsedProp = this.parse(parsedProp.name, 'bezier', propIsBypass);
  }
  if (prop["delete"]) {
    // delete the property and use the default value on falsey value
    style[prop.name] = undefined;
    checkTriggers();
    return true;
  }
  if (prop.deleteBypassed) {
    // delete the property that the
    if (!origProp) {
      checkTriggers();
      return true; // can't delete if no prop
    } else if (origProp.bypass) {
      // delete bypassed
      origProp.bypassed = undefined;
      checkTriggers();
      return true;
    } else {
      return false; // we're unsuccessful deleting the bypassed
    }
  }

  // check if we need to delete the current bypass
  if (prop.deleteBypass) {
    // then this property is just here to indicate we need to delete
    if (!origProp) {
      checkTriggers();
      return true; // property is already not defined
    } else if (origProp.bypass) {
      // then replace the bypass property with the original
      // because the bypassed property was already applied (and therefore parsed), we can just replace it (no reapplying necessary)
      style[prop.name] = origProp.bypassed;
      checkTriggers();
      return true;
    } else {
      return false; // we're unsuccessful deleting the bypass
    }
  }
  var printMappingErr = function printMappingErr() {
    warn('Do not assign mappings to elements without corresponding data (i.e. ele `' + ele.id() + '` has no mapping for property `' + prop.name + '` with data field `' + prop.field + '`); try a `[' + prop.field + ']` selector to limit scope to elements with `' + prop.field + '` defined');
  };

  // put the property in the style objects
  switch (prop.mapped) {
    // flatten the property if mapped
    case types.mapData:
      {
        // flatten the field (e.g. data.foo.bar)
        var fields = prop.field.split('.');
        var fieldVal = _p.data;
        for (var i = 0; i < fields.length && fieldVal; i++) {
          var field = fields[i];
          fieldVal = fieldVal[field];
        }
        if (fieldVal == null) {
          printMappingErr();
          return false;
        }
        var percent;
        if (!number$1(fieldVal)) {
          // then don't apply and fall back on the existing style
          warn('Do not use continuous mappers without specifying numeric data (i.e. `' + prop.field + ': ' + fieldVal + '` for `' + ele.id() + '` is non-numeric)');
          return false;
        } else {
          var fieldWidth = prop.fieldMax - prop.fieldMin;
          if (fieldWidth === 0) {
            // safety check -- not strictly necessary as no props of zero range should be passed here
            percent = 0;
          } else {
            percent = (fieldVal - prop.fieldMin) / fieldWidth;
          }
        }

        // make sure to bound percent value
        if (percent < 0) {
          percent = 0;
        } else if (percent > 1) {
          percent = 1;
        }
        if (type.color) {
          var r1 = prop.valueMin[0];
          var r2 = prop.valueMax[0];
          var g1 = prop.valueMin[1];
          var g2 = prop.valueMax[1];
          var b1 = prop.valueMin[2];
          var b2 = prop.valueMax[2];
          var a1 = prop.valueMin[3] == null ? 1 : prop.valueMin[3];
          var a2 = prop.valueMax[3] == null ? 1 : prop.valueMax[3];
          var clr = [Math.round(r1 + (r2 - r1) * percent), Math.round(g1 + (g2 - g1) * percent), Math.round(b1 + (b2 - b1) * percent), Math.round(a1 + (a2 - a1) * percent)];
          flatProp = {
            // colours are simple, so just create the flat property instead of expensive string parsing
            bypass: prop.bypass,
            // we're a bypass if the mapping property is a bypass
            name: prop.name,
            value: clr,
            strValue: 'rgb(' + clr[0] + ', ' + clr[1] + ', ' + clr[2] + ')'
          };
        } else if (type.number) {
          var calcValue = prop.valueMin + (prop.valueMax - prop.valueMin) * percent;
          flatProp = this.parse(prop.name, calcValue, prop.bypass, flatPropMapping);
        } else {
          return false; // can only map to colours and numbers
        }
        if (!flatProp) {
          // if we can't flatten the property, then don't apply the property and fall back on the existing style
          printMappingErr();
          return false;
        }
        flatProp.mapping = prop; // keep a reference to the mapping
        prop = flatProp; // the flattened (mapped) property is the one we want

        break;
      }

    // direct mapping
    case types.data:
      {
        // flatten the field (e.g. data.foo.bar)
        var _fields = prop.field.split('.');
        var _fieldVal = _p.data;
        for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {
          var _field = _fields[_i3];
          _fieldVal = _fieldVal[_field];
        }
        if (_fieldVal != null) {
          flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);
        }
        if (!flatProp) {
          // if we can't flatten the property, then don't apply and fall back on the existing style
          printMappingErr();
          return false;
        }
        flatProp.mapping = prop; // keep a reference to the mapping
        prop = flatProp; // the flattened (mapped) property is the one we want

        break;
      }
    case types.fn:
      {
        var fn = prop.value;
        var fnRetVal = prop.fnValue != null ? prop.fnValue : fn(ele); // check for cached value before calling function

        prop.prevFnValue = fnRetVal;
        if (fnRetVal == null) {
          warn('Custom function mappers may not return null (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is null)');
          return false;
        }
        flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);
        if (!flatProp) {
          warn('Custom function mappers may not return invalid values for the property type (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is invalid)');
          return false;
        }
        flatProp.mapping = copy(prop); // keep a reference to the mapping
        prop = flatProp; // the flattened (mapped) property is the one we want

        break;
      }
    case undefined:
      break;
    // just set the property

    default:
      return false;
    // not a valid mapping
  }

  // if the property is a bypass property, then link the resultant property to the original one
  if (propIsBypass) {
    if (origPropIsBypass) {
      // then this bypass overrides the existing one
      prop.bypassed = origProp.bypassed; // steal bypassed prop from old bypass
    } else {
      // then link the orig prop to the new bypass
      prop.bypassed = origProp;
    }
    style[prop.name] = prop; // and set
  } else {
    // prop is not bypass
    if (origPropIsBypass) {
      // then keep the orig prop (since it's a bypass) and link to the new prop
      origProp.bypassed = prop;
    } else {
      // then just replace the old prop with the new one
      style[prop.name] = prop;
    }
  }
  checkTriggers();
  return true;
};
styfn$8.cleanElements = function (eles, keepBypasses) {
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    this.clearStyleHints(ele);
    ele.dirtyCompoundBoundsCache();
    ele.dirtyBoundingBoxCache();
    if (!keepBypasses) {
      ele._private.style = {};
    } else {
      var style = ele._private.style;
      var propNames = Object.keys(style);
      for (var j = 0; j < propNames.length; j++) {
        var propName = propNames[j];
        var eleProp = style[propName];
        if (eleProp != null) {
          if (eleProp.bypass) {
            eleProp.bypassed = null;
          } else {
            style[propName] = null;
          }
        }
      }
    }
  }
};

// updates the visual style for all elements (useful for manual style modification after init)
styfn$8.update = function () {
  var cy = this._private.cy;
  var eles = cy.mutableElements();
  eles.updateStyle();
};

// diffProps : { name => { prev, next } }
styfn$8.updateTransitions = function (ele, diffProps) {
  var self = this;
  var _p = ele._private;
  var props = ele.pstyle('transition-property').value;
  var duration = ele.pstyle('transition-duration').pfValue;
  var delay = ele.pstyle('transition-delay').pfValue;
  if (props.length > 0 && duration > 0) {
    var style = {};

    // build up the style to animate towards
    var anyPrev = false;
    for (var i = 0; i < props.length; i++) {
      var prop = props[i];
      var styProp = ele.pstyle(prop);
      var diffProp = diffProps[prop];
      if (!diffProp) {
        continue;
      }
      var prevProp = diffProp.prev;
      var fromProp = prevProp;
      var toProp = diffProp.next != null ? diffProp.next : styProp;
      var diff = false;
      var initVal = undefined;
      var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)

      if (!fromProp) {
        continue;
      }

      // consider px values
      if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {
        diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy
        initVal = fromProp.pfValue + initDt * diff;

        // consider numerical values
      } else if (number$1(fromProp.value) && number$1(toProp.value)) {
        diff = toProp.value - fromProp.value; // nonzero is truthy
        initVal = fromProp.value + initDt * diff;

        // consider colour values
      } else if (array(fromProp.value) && array(toProp.value)) {
        diff = fromProp.value[0] !== toProp.value[0] || fromProp.value[1] !== toProp.value[1] || fromProp.value[2] !== toProp.value[2];
        initVal = fromProp.strValue;
      }

      // the previous value is good for an animation only if it's different
      if (diff) {
        style[prop] = toProp.strValue; // to val
        this.applyBypass(ele, prop, initVal); // from val
        anyPrev = true;
      }
    } // end if props allow ani

    // can't transition if there's nothing previous to transition from
    if (!anyPrev) {
      return;
    }
    _p.transitioning = true;
    new Promise$1(function (resolve) {
      if (delay > 0) {
        ele.delayAnimation(delay).play().promise().then(resolve);
      } else {
        resolve();
      }
    }).then(function () {
      return ele.animation({
        style: style,
        duration: duration,
        easing: ele.pstyle('transition-timing-function').value,
        queue: false
      }).play().promise();
    }).then(function () {
      // if( !isBypass ){
      self.removeBypasses(ele, props);
      ele.emitAndNotify('style');
      // }

      _p.transitioning = false;
    });
  } else if (_p.transitioning) {
    this.removeBypasses(ele, props);
    ele.emitAndNotify('style');
    _p.transitioning = false;
  }
};
styfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {
  var prop = this.properties[name];
  var triggerCheck = getTrigger(prop);
  if (ele.removed()) {
    return;
  }
  if (triggerCheck != null && triggerCheck(fromValue, toValue, ele)) {
    onTrigger(prop);
  }
};
styfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {
  var _this = this;
  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
    return prop.triggersZOrder;
  }, function () {
    _this._private.cy.notify('zorder', ele);
  });
};
styfn$8.checkBoundsTrigger = function (ele, name, fromValue, toValue) {
  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
    return prop.triggersBounds;
  }, function (prop) {
    ele.dirtyCompoundBoundsCache();
    ele.dirtyBoundingBoxCache();
  });
};
styfn$8.checkConnectedEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
    return prop.triggersBoundsOfConnectedEdges;
  }, function (prop) {
    ele.connectedEdges().forEach(function (edge) {
      edge.dirtyBoundingBoxCache();
    });
  });
};
styfn$8.checkParallelEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
    return prop.triggersBoundsOfParallelEdges;
  }, function (prop) {
    ele.parallelEdges().forEach(function (pllEdge) {
      pllEdge.dirtyBoundingBoxCache();
    });
  });
};
styfn$8.checkTriggers = function (ele, name, fromValue, toValue) {
  ele.dirtyStyleCache();
  this.checkZOrderTrigger(ele, name, fromValue, toValue);
  this.checkBoundsTrigger(ele, name, fromValue, toValue);
  this.checkConnectedEdgesBoundsTrigger(ele, name, fromValue, toValue);
  this.checkParallelEdgesBoundsTrigger(ele, name, fromValue, toValue);
};

var styfn$7 = {};

// bypasses are applied to an existing style on an element, and just tacked on temporarily
// returns true iff application was successful for at least 1 specified property
styfn$7.applyBypass = function (eles, name, value, updateTransitions) {
  var self = this;
  var props = [];
  var isBypass = true;

  // put all the properties (can specify one or many) in an array after parsing them
  if (name === '*' || name === '**') {
    // apply to all property names

    if (value !== undefined) {
      for (var i = 0; i < self.properties.length; i++) {
        var prop = self.properties[i];
        var _name = prop.name;
        var parsedProp = this.parse(_name, value, true);
        if (parsedProp) {
          props.push(parsedProp);
        }
      }
    }
  } else if (string(name)) {
    // then parse the single property
    var _parsedProp = this.parse(name, value, true);
    if (_parsedProp) {
      props.push(_parsedProp);
    }
  } else if (plainObject(name)) {
    // then parse each property
    var specifiedProps = name;
    updateTransitions = value;
    var names = Object.keys(specifiedProps);
    for (var _i = 0; _i < names.length; _i++) {
      var _name2 = names[_i];
      var _value = specifiedProps[_name2];
      if (_value === undefined) {
        // try camel case name too
        _value = specifiedProps[dash2camel(_name2)];
      }
      if (_value !== undefined) {
        var _parsedProp2 = this.parse(_name2, _value, true);
        if (_parsedProp2) {
          props.push(_parsedProp2);
        }
      }
    }
  } else {
    // can't do anything without well defined properties
    return false;
  }

  // we've failed if there are no valid properties
  if (props.length === 0) {
    return false;
  }

  // now, apply the bypass properties on the elements
  var ret = false; // return true if at least one succesful bypass applied
  for (var _i2 = 0; _i2 < eles.length; _i2++) {
    // for each ele
    var ele = eles[_i2];
    var diffProps = {};
    var diffProp = undefined;
    for (var j = 0; j < props.length; j++) {
      // for each prop
      var _prop = props[j];
      if (updateTransitions) {
        var prevProp = ele.pstyle(_prop.name);
        diffProp = diffProps[_prop.name] = {
          prev: prevProp
        };
      }
      ret = this.applyParsedProperty(ele, copy(_prop)) || ret;
      if (updateTransitions) {
        diffProp.next = ele.pstyle(_prop.name);
      }
    } // for props

    if (ret) {
      this.updateStyleHints(ele);
    }
    if (updateTransitions) {
      this.updateTransitions(ele, diffProps, isBypass);
    }
  } // for eles

  return ret;
};

// only useful in specific cases like animation
styfn$7.overrideBypass = function (eles, name, value) {
  name = camel2dash(name);
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    var prop = ele._private.style[name];
    var type = this.properties[name].type;
    var isColor = type.color;
    var isMulti = type.mutiple;
    var oldValue = !prop ? null : prop.pfValue != null ? prop.pfValue : prop.value;
    if (!prop || !prop.bypass) {
      // need a bypass if one doesn't exist
      this.applyBypass(ele, name, value);
    } else {
      prop.value = value;
      if (prop.pfValue != null) {
        prop.pfValue = value;
      }
      if (isColor) {
        prop.strValue = 'rgb(' + value.join(',') + ')';
      } else if (isMulti) {
        prop.strValue = value.join(' ');
      } else {
        prop.strValue = '' + value;
      }
      this.updateStyleHints(ele);
    }
    this.checkTriggers(ele, name, oldValue, value);
  }
};
styfn$7.removeAllBypasses = function (eles, updateTransitions) {
  return this.removeBypasses(eles, this.propertyNames, updateTransitions);
};
styfn$7.removeBypasses = function (eles, props, updateTransitions) {
  var isBypass = true;
  for (var j = 0; j < eles.length; j++) {
    var ele = eles[j];
    var diffProps = {};
    for (var i = 0; i < props.length; i++) {
      var name = props[i];
      var prop = this.properties[name];
      var prevProp = ele.pstyle(prop.name);
      if (!prevProp || !prevProp.bypass) {
        // if a bypass doesn't exist for the prop, nothing needs to be removed
        continue;
      }
      var value = ''; // empty => remove bypass
      var parsedProp = this.parse(name, value, true);
      var diffProp = diffProps[prop.name] = {
        prev: prevProp
      };
      this.applyParsedProperty(ele, parsedProp);
      diffProp.next = ele.pstyle(prop.name);
    } // for props

    this.updateStyleHints(ele);
    if (updateTransitions) {
      this.updateTransitions(ele, diffProps, isBypass);
    }
  } // for eles
};

var styfn$6 = {};

// gets what an em size corresponds to in pixels relative to a dom element
styfn$6.getEmSizeInPixels = function () {
  var px = this.containerCss('font-size');
  if (px != null) {
    return parseFloat(px);
  } else {
    return 1; // for headless
  }
};

// gets css property from the core container
styfn$6.containerCss = function (propName) {
  var cy = this._private.cy;
  var domElement = cy.container();
  var containerWindow = cy.window();
  if (containerWindow && domElement && containerWindow.getComputedStyle) {
    return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);
  }
};

var styfn$5 = {};

// gets the rendered style for an element
styfn$5.getRenderedStyle = function (ele, prop) {
  if (prop) {
    return this.getStylePropertyValue(ele, prop, true);
  } else {
    return this.getRawStyle(ele, true);
  }
};

// gets the raw style for an element
styfn$5.getRawStyle = function (ele, isRenderedVal) {
  var self = this;
  ele = ele[0]; // insure it's an element

  if (ele) {
    var rstyle = {};
    for (var i = 0; i < self.properties.length; i++) {
      var prop = self.properties[i];
      var val = self.getStylePropertyValue(ele, prop.name, isRenderedVal);
      if (val != null) {
        rstyle[prop.name] = val;
        rstyle[dash2camel(prop.name)] = val;
      }
    }
    return rstyle;
  }
};
styfn$5.getIndexedStyle = function (ele, property, subproperty, index) {
  var pstyle = ele.pstyle(property)[subproperty][index];
  return pstyle != null ? pstyle : ele.cy().style().getDefaultProperty(property)[subproperty][0];
};
styfn$5.getStylePropertyValue = function (ele, propName, isRenderedVal) {
  var self = this;
  ele = ele[0]; // insure it's an element

  if (ele) {
    var prop = self.properties[propName];
    if (prop.alias) {
      prop = prop.pointsTo;
    }
    var type = prop.type;
    var styleProp = ele.pstyle(prop.name);
    if (styleProp) {
      var value = styleProp.value,
        units = styleProp.units,
        strValue = styleProp.strValue;
      if (isRenderedVal && type.number && value != null && number$1(value)) {
        var zoom = ele.cy().zoom();
        var getRenderedValue = function getRenderedValue(val) {
          return val * zoom;
        };
        var getValueStringWithUnits = function getValueStringWithUnits(val, units) {
          return getRenderedValue(val) + units;
        };
        var isArrayValue = array(value);
        var haveUnits = isArrayValue ? units.every(function (u) {
          return u != null;
        }) : units != null;
        if (haveUnits) {
          if (isArrayValue) {
            return value.map(function (v, i) {
              return getValueStringWithUnits(v, units[i]);
            }).join(' ');
          } else {
            return getValueStringWithUnits(value, units);
          }
        } else {
          if (isArrayValue) {
            return value.map(function (v) {
              return string(v) ? v : '' + getRenderedValue(v);
            }).join(' ');
          } else {
            return '' + getRenderedValue(value);
          }
        }
      } else if (strValue != null) {
        return strValue;
      }
    }
    return null;
  }
};
styfn$5.getAnimationStartStyle = function (ele, aniProps) {
  var rstyle = {};
  for (var i = 0; i < aniProps.length; i++) {
    var aniProp = aniProps[i];
    var name = aniProp.name;
    var styleProp = ele.pstyle(name);
    if (styleProp !== undefined) {
      // then make a prop of it
      if (plainObject(styleProp)) {
        styleProp = this.parse(name, styleProp.strValue);
      } else {
        styleProp = this.parse(name, styleProp);
      }
    }
    if (styleProp) {
      rstyle[name] = styleProp;
    }
  }
  return rstyle;
};
styfn$5.getPropsList = function (propsObj) {
  var self = this;
  var rstyle = [];
  var style = propsObj;
  var props = self.properties;
  if (style) {
    var names = Object.keys(style);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      var val = style[name];
      var prop = props[name] || props[camel2dash(name)];
      var styleProp = this.parse(prop.name, val);
      if (styleProp) {
        rstyle.push(styleProp);
      }
    }
  }
  return rstyle;
};
styfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {
  var hash = seed.slice();
  var name, val, strVal, chVal;
  var i, j;
  for (i = 0; i < propNames.length; i++) {
    name = propNames[i];
    val = ele.pstyle(name, false);
    if (val == null) {
      continue;
    } else if (val.pfValue != null) {
      hash[0] = hashInt(chVal, hash[0]);
      hash[1] = hashIntAlt(chVal, hash[1]);
    } else {
      strVal = val.strValue;
      for (j = 0; j < strVal.length; j++) {
        chVal = strVal.charCodeAt(j);
        hash[0] = hashInt(chVal, hash[0]);
        hash[1] = hashIntAlt(chVal, hash[1]);
      }
    }
  }
  return hash;
};
styfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;

var styfn$4 = {};
styfn$4.appendFromJson = function (json) {
  var style = this;
  for (var i = 0; i < json.length; i++) {
    var context = json[i];
    var selector = context.selector;
    var props = context.style || context.css;
    var names = Object.keys(props);
    style.selector(selector); // apply selector

    for (var j = 0; j < names.length; j++) {
      var name = names[j];
      var value = props[name];
      style.css(name, value); // apply property
    }
  }
  return style;
};

// accessible cy.style() function
styfn$4.fromJson = function (json) {
  var style = this;
  style.resetToDefault();
  style.appendFromJson(json);
  return style;
};

// get json from cy.style() api
styfn$4.json = function () {
  var json = [];
  for (var i = this.defaultLength; i < this.length; i++) {
    var cxt = this[i];
    var selector = cxt.selector;
    var props = cxt.properties;
    var css = {};
    for (var j = 0; j < props.length; j++) {
      var prop = props[j];
      css[prop.name] = prop.strValue;
    }
    json.push({
      selector: !selector ? 'core' : selector.toString(),
      style: css
    });
  }
  return json;
};

var styfn$3 = {};
styfn$3.appendFromString = function (string) {
  var self = this;
  var style = this;
  var remaining = '' + string;
  var selAndBlockStr;
  var blockRem;
  var propAndValStr;

  // remove comments from the style string
  remaining = remaining.replace(/[/][*](\s|.)+?[*][/]/g, '');
  function removeSelAndBlockFromRemaining() {
    // remove the parsed selector and block from the remaining text to parse
    if (remaining.length > selAndBlockStr.length) {
      remaining = remaining.substr(selAndBlockStr.length);
    } else {
      remaining = '';
    }
  }
  function removePropAndValFromRem() {
    // remove the parsed property and value from the remaining block text to parse
    if (blockRem.length > propAndValStr.length) {
      blockRem = blockRem.substr(propAndValStr.length);
    } else {
      blockRem = '';
    }
  }
  for (;;) {
    var nothingLeftToParse = remaining.match(/^\s*$/);
    if (nothingLeftToParse) {
      break;
    }
    var selAndBlock = remaining.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);
    if (!selAndBlock) {
      warn('Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: ' + remaining);
      break;
    }
    selAndBlockStr = selAndBlock[0];

    // parse the selector
    var selectorStr = selAndBlock[1];
    if (selectorStr !== 'core') {
      var selector = new Selector(selectorStr);
      if (selector.invalid) {
        warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr);

        // skip this selector and block
        removeSelAndBlockFromRemaining();
        continue;
      }
    }

    // parse the block of properties and values
    var blockStr = selAndBlock[2];
    var invalidBlock = false;
    blockRem = blockStr;
    var props = [];
    for (;;) {
      var _nothingLeftToParse = blockRem.match(/^\s*$/);
      if (_nothingLeftToParse) {
        break;
      }
      var propAndVal = blockRem.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);
      if (!propAndVal) {
        warn('Skipping parsing of block: Invalid formatting of style property and value definitions found in:' + blockStr);
        invalidBlock = true;
        break;
      }
      propAndValStr = propAndVal[0];
      var propStr = propAndVal[1];
      var valStr = propAndVal[2];
      var prop = self.properties[propStr];
      if (!prop) {
        warn('Skipping property: Invalid property name in: ' + propAndValStr);

        // skip this property in the block
        removePropAndValFromRem();
        continue;
      }
      var parsedProp = style.parse(propStr, valStr);
      if (!parsedProp) {
        warn('Skipping property: Invalid property definition in: ' + propAndValStr);

        // skip this property in the block
        removePropAndValFromRem();
        continue;
      }
      props.push({
        name: propStr,
        val: valStr
      });
      removePropAndValFromRem();
    }
    if (invalidBlock) {
      removeSelAndBlockFromRemaining();
      break;
    }

    // put the parsed block in the style
    style.selector(selectorStr);
    for (var i = 0; i < props.length; i++) {
      var _prop = props[i];
      style.css(_prop.name, _prop.val);
    }
    removeSelAndBlockFromRemaining();
  }
  return style;
};
styfn$3.fromString = function (string) {
  var style = this;
  style.resetToDefault();
  style.appendFromString(string);
  return style;
};

var styfn$2 = {};
(function () {
  var number$1 = number;
  var rgba = rgbaNoBackRefs;
  var hsla = hslaNoBackRefs;
  var hex3$1 = hex3;
  var hex6$1 = hex6;
  var data = function data(prefix) {
    return '^' + prefix + '\\s*\\(\\s*([\\w\\.]+)\\s*\\)$';
  };
  var mapData = function mapData(prefix) {
    var mapArg = number$1 + '|\\w+|' + rgba + '|' + hsla + '|' + hex3$1 + '|' + hex6$1;
    return '^' + prefix + '\\s*\\(([\\w\\.]+)\\s*\\,\\s*(' + number$1 + ')\\s*\\,\\s*(' + number$1 + ')\\s*,\\s*(' + mapArg + ')\\s*\\,\\s*(' + mapArg + ')\\)$';
  };
  var urlRegexes = ['^url\\s*\\(\\s*[\'"]?(.+?)[\'"]?\\s*\\)$', '^(none)$', '^(.+)$'];

  // each visual style property has a type and needs to be validated according to it
  styfn$2.types = {
    time: {
      number: true,
      min: 0,
      units: 's|ms',
      implicitUnits: 'ms'
    },
    percent: {
      number: true,
      min: 0,
      max: 100,
      units: '%',
      implicitUnits: '%'
    },
    percentages: {
      number: true,
      min: 0,
      max: 100,
      units: '%',
      implicitUnits: '%',
      multiple: true
    },
    zeroOneNumber: {
      number: true,
      min: 0,
      max: 1,
      unitless: true
    },
    zeroOneNumbers: {
      number: true,
      min: 0,
      max: 1,
      unitless: true,
      multiple: true
    },
    nOneOneNumber: {
      number: true,
      min: -1,
      max: 1,
      unitless: true
    },
    nonNegativeInt: {
      number: true,
      min: 0,
      integer: true,
      unitless: true
    },
    nonNegativeNumber: {
      number: true,
      min: 0,
      unitless: true
    },
    position: {
      enums: ['parent', 'origin']
    },
    nodeSize: {
      number: true,
      min: 0,
      enums: ['label']
    },
    number: {
      number: true,
      unitless: true
    },
    numbers: {
      number: true,
      unitless: true,
      multiple: true
    },
    positiveNumber: {
      number: true,
      unitless: true,
      min: 0,
      strictMin: true
    },
    size: {
      number: true,
      min: 0
    },
    bidirectionalSize: {
      number: true
    },
    // allows negative
    bidirectionalSizeMaybePercent: {
      number: true,
      allowPercent: true
    },
    // allows negative
    bidirectionalSizes: {
      number: true,
      multiple: true
    },
    // allows negative
    sizeMaybePercent: {
      number: true,
      min: 0,
      allowPercent: true
    },
    axisDirection: {
      enums: ['horizontal', 'leftward', 'rightward', 'vertical', 'upward', 'downward', 'auto']
    },
    axisDirectionExplicit: {
      enums: ['leftward', 'rightward', 'upward', 'downward']
    },
    axisDirectionPrimary: {
      enums: ['horizontal', 'vertical']
    },
    paddingRelativeTo: {
      enums: ['width', 'height', 'average', 'min', 'max']
    },
    bgWH: {
      number: true,
      min: 0,
      allowPercent: true,
      enums: ['auto'],
      multiple: true
    },
    bgPos: {
      number: true,
      allowPercent: true,
      multiple: true
    },
    bgRelativeTo: {
      enums: ['inner', 'include-padding'],
      multiple: true
    },
    bgRepeat: {
      enums: ['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],
      multiple: true
    },
    bgFit: {
      enums: ['none', 'contain', 'cover'],
      multiple: true
    },
    bgCrossOrigin: {
      enums: ['anonymous', 'use-credentials', 'null'],
      multiple: true
    },
    bgClip: {
      enums: ['none', 'node'],
      multiple: true
    },
    bgContainment: {
      enums: ['inside', 'over'],
      multiple: true
    },
    boxSelection: {
      enums: ['contain', 'overlap', 'none']
    },
    color: {
      color: true
    },
    colors: {
      color: true,
      multiple: true
    },
    fill: {
      enums: ['solid', 'linear-gradient', 'radial-gradient']
    },
    bool: {
      enums: ['yes', 'no']
    },
    bools: {
      enums: ['yes', 'no'],
      multiple: true
    },
    lineStyle: {
      enums: ['solid', 'dotted', 'dashed']
    },
    lineCap: {
      enums: ['butt', 'round', 'square']
    },
    linePosition: {
      enums: ['center', 'inside', 'outside']
    },
    lineJoin: {
      enums: ['round', 'bevel', 'miter']
    },
    borderStyle: {
      enums: ['solid', 'dotted', 'dashed', 'double']
    },
    curveStyle: {
      enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi', 'round-segments', 'round-taxi']
    },
    radiusType: {
      enums: ['arc-radius', 'influence-radius'],
      multiple: true
    },
    fontFamily: {
      regex: '^([\\w- \\"]+(?:\\s*,\\s*[\\w- \\"]+)*)$'
    },
    fontStyle: {
      enums: ['italic', 'normal', 'oblique']
    },
    fontWeight: {
      enums: ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '800', '900', 100, 200, 300, 400, 500, 600, 700, 800, 900]
    },
    textDecoration: {
      enums: ['none', 'underline', 'overline', 'line-through']
    },
    textTransform: {
      enums: ['none', 'uppercase', 'lowercase']
    },
    textWrap: {
      enums: ['none', 'wrap', 'ellipsis']
    },
    textOverflowWrap: {
      enums: ['whitespace', 'anywhere']
    },
    textBackgroundShape: {
      enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'circle']
    },
    nodeShape: {
      enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'cutrectangle', 'cut-rectangle', 'bottomroundrectangle', 'bottom-round-rectangle', 'barrel', 'ellipse', 'triangle', 'round-triangle', 'square', 'pentagon', 'round-pentagon', 'hexagon', 'round-hexagon', 'concavehexagon', 'concave-hexagon', 'heptagon', 'round-heptagon', 'octagon', 'round-octagon', 'tag', 'round-tag', 'star', 'diamond', 'round-diamond', 'vee', 'rhomboid', 'right-rhomboid', 'polygon']
    },
    overlayShape: {
      enums: ['roundrectangle', 'round-rectangle', 'ellipse']
    },
    cornerRadius: {
      number: true,
      min: 0,
      units: 'px|em',
      implicitUnits: 'px',
      enums: ['auto']
    },
    compoundIncludeLabels: {
      enums: ['include', 'exclude']
    },
    arrowShape: {
      enums: ['tee', 'triangle', 'triangle-tee', 'circle-triangle', 'triangle-cross', 'triangle-backcurve', 'vee', 'square', 'circle', 'diamond', 'chevron', 'none']
    },
    arrowFill: {
      enums: ['filled', 'hollow']
    },
    arrowWidth: {
      number: true,
      units: '%|px|em',
      implicitUnits: 'px',
      enums: ['match-line']
    },
    display: {
      enums: ['element', 'none']
    },
    visibility: {
      enums: ['hidden', 'visible']
    },
    zCompoundDepth: {
      enums: ['bottom', 'orphan', 'auto', 'top']
    },
    zIndexCompare: {
      enums: ['auto', 'manual']
    },
    valign: {
      enums: ['top', 'center', 'bottom']
    },
    halign: {
      enums: ['left', 'center', 'right']
    },
    justification: {
      enums: ['left', 'center', 'right', 'auto']
    },
    text: {
      string: true
    },
    data: {
      mapping: true,
      regex: data('data')
    },
    layoutData: {
      mapping: true,
      regex: data('layoutData')
    },
    scratch: {
      mapping: true,
      regex: data('scratch')
    },
    mapData: {
      mapping: true,
      regex: mapData('mapData')
    },
    mapLayoutData: {
      mapping: true,
      regex: mapData('mapLayoutData')
    },
    mapScratch: {
      mapping: true,
      regex: mapData('mapScratch')
    },
    fn: {
      mapping: true,
      fn: true
    },
    url: {
      regexes: urlRegexes,
      singleRegexMatchValue: true
    },
    urls: {
      regexes: urlRegexes,
      singleRegexMatchValue: true,
      multiple: true
    },
    propList: {
      propList: true
    },
    angle: {
      number: true,
      units: 'deg|rad',
      implicitUnits: 'rad'
    },
    textRotation: {
      number: true,
      units: 'deg|rad',
      implicitUnits: 'rad',
      enums: ['none', 'autorotate']
    },
    polygonPointList: {
      number: true,
      multiple: true,
      evenMultiple: true,
      min: -1,
      max: 1,
      unitless: true
    },
    edgeDistances: {
      enums: ['intersection', 'node-position', 'endpoints']
    },
    edgeEndpoint: {
      number: true,
      multiple: true,
      units: '%|px|em|deg|rad',
      implicitUnits: 'px',
      enums: ['inside-to-node', 'outside-to-node', 'outside-to-node-or-label', 'outside-to-line', 'outside-to-line-or-label'],
      singleEnum: true,
      validate: function validate(valArr, unitsArr) {
        switch (valArr.length) {
          case 2:
            // can be % or px only
            return unitsArr[0] !== 'deg' && unitsArr[0] !== 'rad' && unitsArr[1] !== 'deg' && unitsArr[1] !== 'rad';
          case 1:
            // can be enum, deg, or rad only
            return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';
          default:
            return false;
        }
      }
    },
    easing: {
      regexes: ['^(spring)\\s*\\(\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*\\)$', '^(cubic-bezier)\\s*\\(\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*\\)$'],
      enums: ['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'ease-in-sine', 'ease-out-sine', 'ease-in-out-sine', 'ease-in-quad', 'ease-out-quad', 'ease-in-out-quad', 'ease-in-cubic', 'ease-out-cubic', 'ease-in-out-cubic', 'ease-in-quart', 'ease-out-quart', 'ease-in-out-quart', 'ease-in-quint', 'ease-out-quint', 'ease-in-out-quint', 'ease-in-expo', 'ease-out-expo', 'ease-in-out-expo', 'ease-in-circ', 'ease-out-circ', 'ease-in-out-circ']
    },
    gradientDirection: {
      enums: ['to-bottom', 'to-top', 'to-left', 'to-right', 'to-bottom-right', 'to-bottom-left', 'to-top-right', 'to-top-left', 'to-right-bottom', 'to-left-bottom', 'to-right-top', 'to-left-top' // different order
      ]
    },
    boundsExpansion: {
      number: true,
      multiple: true,
      min: 0,
      validate: function validate(valArr) {
        var length = valArr.length;
        return length === 1 || length === 2 || length === 4;
      }
    }
  };
  var diff = {
    zeroNonZero: function zeroNonZero(val1, val2) {
      if ((val1 == null || val2 == null) && val1 !== val2) {
        return true; // null cases could represent any value
      }
      if (val1 == 0 && val2 != 0) {
        return true;
      } else if (val1 != 0 && val2 == 0) {
        return true;
      } else {
        return false;
      }
    },
    any: function any(val1, val2) {
      return val1 != val2;
    },
    emptyNonEmpty: function emptyNonEmpty(str1, str2) {
      var empty1 = emptyString(str1);
      var empty2 = emptyString(str2);
      return empty1 && !empty2 || !empty1 && empty2;
    }
  };

  // define visual style properties
  //
  // - n.b. adding a new group of props may require updates to updateStyleHints()
  // - adding new props to an existing group gets handled automatically

  var t = styfn$2.types;
  var mainLabel = [{
    name: 'label',
    type: t.text,
    triggersBounds: diff.any,
    triggersZOrder: diff.emptyNonEmpty
  }, {
    name: 'text-rotation',
    type: t.textRotation,
    triggersBounds: diff.any
  }, {
    name: 'text-margin-x',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'text-margin-y',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }];
  var sourceLabel = [{
    name: 'source-label',
    type: t.text,
    triggersBounds: diff.any
  }, {
    name: 'source-text-rotation',
    type: t.textRotation,
    triggersBounds: diff.any
  }, {
    name: 'source-text-margin-x',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'source-text-margin-y',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'source-text-offset',
    type: t.size,
    triggersBounds: diff.any
  }];
  var targetLabel = [{
    name: 'target-label',
    type: t.text,
    triggersBounds: diff.any
  }, {
    name: 'target-text-rotation',
    type: t.textRotation,
    triggersBounds: diff.any
  }, {
    name: 'target-text-margin-x',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'target-text-margin-y',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'target-text-offset',
    type: t.size,
    triggersBounds: diff.any
  }];
  var labelDimensions = [{
    name: 'font-family',
    type: t.fontFamily,
    triggersBounds: diff.any
  }, {
    name: 'font-style',
    type: t.fontStyle,
    triggersBounds: diff.any
  }, {
    name: 'font-weight',
    type: t.fontWeight,
    triggersBounds: diff.any
  }, {
    name: 'font-size',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'text-transform',
    type: t.textTransform,
    triggersBounds: diff.any
  }, {
    name: 'text-wrap',
    type: t.textWrap,
    triggersBounds: diff.any
  }, {
    name: 'text-overflow-wrap',
    type: t.textOverflowWrap,
    triggersBounds: diff.any
  }, {
    name: 'text-max-width',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'text-outline-width',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'line-height',
    type: t.positiveNumber,
    triggersBounds: diff.any
  }];
  var commonLabel = [{
    name: 'text-valign',
    type: t.valign,
    triggersBounds: diff.any
  }, {
    name: 'text-halign',
    type: t.halign,
    triggersBounds: diff.any
  }, {
    name: 'color',
    type: t.color
  }, {
    name: 'text-outline-color',
    type: t.color
  }, {
    name: 'text-outline-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'text-background-color',
    type: t.color
  }, {
    name: 'text-background-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'text-background-padding',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'text-border-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'text-border-color',
    type: t.color
  }, {
    name: 'text-border-width',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'text-border-style',
    type: t.borderStyle,
    triggersBounds: diff.any
  }, {
    name: 'text-background-shape',
    type: t.textBackgroundShape,
    triggersBounds: diff.any
  }, {
    name: 'text-justification',
    type: t.justification
  }, {
    name: 'box-select-labels',
    type: t.bool,
    triggersBounds: diff.any
  }];
  var behavior = [{
    name: 'events',
    type: t.bool,
    triggersZOrder: diff.any
  }, {
    name: 'text-events',
    type: t.bool,
    triggersZOrder: diff.any
  }, {
    name: 'box-selection',
    type: t.boxSelection,
    triggersZOrder: diff.any
  }];
  var visibility = [{
    name: 'display',
    type: t.display,
    triggersZOrder: diff.any,
    triggersBounds: diff.any,
    triggersBoundsOfConnectedEdges: diff.any,
    triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue, ele) {
      if (fromValue === toValue) {
        return false;
      }

      // only if edge is bundled bezier (so as not to affect performance of other edges)
      return ele.pstyle('curve-style').value === 'bezier';
    }
  }, {
    name: 'visibility',
    type: t.visibility,
    triggersZOrder: diff.any
  }, {
    name: 'opacity',
    type: t.zeroOneNumber,
    triggersZOrder: diff.zeroNonZero
  }, {
    name: 'text-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'min-zoomed-font-size',
    type: t.size
  }, {
    name: 'z-compound-depth',
    type: t.zCompoundDepth,
    triggersZOrder: diff.any
  }, {
    name: 'z-index-compare',
    type: t.zIndexCompare,
    triggersZOrder: diff.any
  }, {
    name: 'z-index',
    type: t.number,
    triggersZOrder: diff.any
  }];
  var overlay = [{
    name: 'overlay-padding',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'overlay-color',
    type: t.color
  }, {
    name: 'overlay-opacity',
    type: t.zeroOneNumber,
    triggersBounds: diff.zeroNonZero
  }, {
    name: 'overlay-shape',
    type: t.overlayShape,
    triggersBounds: diff.any
  }, {
    name: 'overlay-corner-radius',
    type: t.cornerRadius
  }];
  var underlay = [{
    name: 'underlay-padding',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'underlay-color',
    type: t.color
  }, {
    name: 'underlay-opacity',
    type: t.zeroOneNumber,
    triggersBounds: diff.zeroNonZero
  }, {
    name: 'underlay-shape',
    type: t.overlayShape,
    triggersBounds: diff.any
  }, {
    name: 'underlay-corner-radius',
    type: t.cornerRadius
  }];
  var transition = [{
    name: 'transition-property',
    type: t.propList
  }, {
    name: 'transition-duration',
    type: t.time
  }, {
    name: 'transition-delay',
    type: t.time
  }, {
    name: 'transition-timing-function',
    type: t.easing
  }];
  var nodeSizeHashOverride = function nodeSizeHashOverride(ele, parsedProp) {
    if (parsedProp.value === 'label') {
      return -ele.poolIndex(); // no hash key hits is using label size (hitrate for perf probably low anyway)
    } else {
      return parsedProp.pfValue;
    }
  };
  var nodeBody = [{
    name: 'height',
    type: t.nodeSize,
    triggersBounds: diff.any,
    hashOverride: nodeSizeHashOverride
  }, {
    name: 'width',
    type: t.nodeSize,
    triggersBounds: diff.any,
    hashOverride: nodeSizeHashOverride
  }, {
    name: 'shape',
    type: t.nodeShape,
    triggersBounds: diff.any
  }, {
    name: 'shape-polygon-points',
    type: t.polygonPointList,
    triggersBounds: diff.any
  }, {
    name: 'corner-radius',
    type: t.cornerRadius
  }, {
    name: 'background-color',
    type: t.color
  }, {
    name: 'background-fill',
    type: t.fill
  }, {
    name: 'background-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'background-blacken',
    type: t.nOneOneNumber
  }, {
    name: 'background-gradient-stop-colors',
    type: t.colors
  }, {
    name: 'background-gradient-stop-positions',
    type: t.percentages
  }, {
    name: 'background-gradient-direction',
    type: t.gradientDirection
  }, {
    name: 'padding',
    type: t.sizeMaybePercent,
    triggersBounds: diff.any
  }, {
    name: 'padding-relative-to',
    type: t.paddingRelativeTo,
    triggersBounds: diff.any
  }, {
    name: 'bounds-expansion',
    type: t.boundsExpansion,
    triggersBounds: diff.any
  }];
  var nodeBorder = [{
    name: 'border-color',
    type: t.color
  }, {
    name: 'border-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'border-width',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'border-style',
    type: t.borderStyle
  }, {
    name: 'border-cap',
    type: t.lineCap
  }, {
    name: 'border-join',
    type: t.lineJoin
  }, {
    name: 'border-dash-pattern',
    type: t.numbers
  }, {
    name: 'border-dash-offset',
    type: t.number
  }, {
    name: 'border-position',
    type: t.linePosition
  }];
  var nodeOutline = [{
    name: 'outline-color',
    type: t.color
  }, {
    name: 'outline-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'outline-width',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'outline-style',
    type: t.borderStyle
  }, {
    name: 'outline-offset',
    type: t.size,
    triggersBounds: diff.any
  }];
  var backgroundImage = [{
    name: 'background-image',
    type: t.urls
  }, {
    name: 'background-image-crossorigin',
    type: t.bgCrossOrigin
  }, {
    name: 'background-image-opacity',
    type: t.zeroOneNumbers
  }, {
    name: 'background-image-containment',
    type: t.bgContainment
  }, {
    name: 'background-image-smoothing',
    type: t.bools
  }, {
    name: 'background-position-x',
    type: t.bgPos
  }, {
    name: 'background-position-y',
    type: t.bgPos
  }, {
    name: 'background-width-relative-to',
    type: t.bgRelativeTo
  }, {
    name: 'background-height-relative-to',
    type: t.bgRelativeTo
  }, {
    name: 'background-repeat',
    type: t.bgRepeat
  }, {
    name: 'background-fit',
    type: t.bgFit
  }, {
    name: 'background-clip',
    type: t.bgClip
  }, {
    name: 'background-width',
    type: t.bgWH
  }, {
    name: 'background-height',
    type: t.bgWH
  }, {
    name: 'background-offset-x',
    type: t.bgPos
  }, {
    name: 'background-offset-y',
    type: t.bgPos
  }];
  var compound = [{
    name: 'position',
    type: t.position,
    triggersBounds: diff.any
  }, {
    name: 'compound-sizing-wrt-labels',
    type: t.compoundIncludeLabels,
    triggersBounds: diff.any
  }, {
    name: 'min-width',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'min-width-bias-left',
    type: t.sizeMaybePercent,
    triggersBounds: diff.any
  }, {
    name: 'min-width-bias-right',
    type: t.sizeMaybePercent,
    triggersBounds: diff.any
  }, {
    name: 'min-height',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'min-height-bias-top',
    type: t.sizeMaybePercent,
    triggersBounds: diff.any
  }, {
    name: 'min-height-bias-bottom',
    type: t.sizeMaybePercent,
    triggersBounds: diff.any
  }];
  var edgeLine = [{
    name: 'line-style',
    type: t.lineStyle
  }, {
    name: 'line-color',
    type: t.color
  }, {
    name: 'line-fill',
    type: t.fill
  }, {
    name: 'line-cap',
    type: t.lineCap
  }, {
    name: 'line-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'line-dash-pattern',
    type: t.numbers
  }, {
    name: 'line-dash-offset',
    type: t.number
  }, {
    name: 'line-outline-width',
    type: t.size
  }, {
    name: 'line-outline-color',
    type: t.color
  }, {
    name: 'line-gradient-stop-colors',
    type: t.colors
  }, {
    name: 'line-gradient-stop-positions',
    type: t.percentages
  }, {
    name: 'curve-style',
    type: t.curveStyle,
    triggersBounds: diff.any,
    triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue) {
      if (fromValue === toValue) {
        return false;
      } // must have diff

      return fromValue === 'bezier' ||
      // remove from bundle
      toValue === 'bezier'; // add to bundle
    }
  }, {
    name: 'haystack-radius',
    type: t.zeroOneNumber,
    triggersBounds: diff.any
  }, {
    name: 'source-endpoint',
    type: t.edgeEndpoint,
    triggersBounds: diff.any
  }, {
    name: 'target-endpoint',
    type: t.edgeEndpoint,
    triggersBounds: diff.any
  }, {
    name: 'control-point-step-size',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'control-point-distances',
    type: t.bidirectionalSizes,
    triggersBounds: diff.any
  }, {
    name: 'control-point-weights',
    type: t.numbers,
    triggersBounds: diff.any
  }, {
    name: 'segment-distances',
    type: t.bidirectionalSizes,
    triggersBounds: diff.any
  }, {
    name: 'segment-weights',
    type: t.numbers,
    triggersBounds: diff.any
  }, {
    name: 'segment-radii',
    type: t.numbers,
    triggersBounds: diff.any
  }, {
    name: 'radius-type',
    type: t.radiusType,
    triggersBounds: diff.any
  }, {
    name: 'taxi-turn',
    type: t.bidirectionalSizeMaybePercent,
    triggersBounds: diff.any
  }, {
    name: 'taxi-turn-min-distance',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'taxi-direction',
    type: t.axisDirection,
    triggersBounds: diff.any
  }, {
    name: 'taxi-radius',
    type: t.number,
    triggersBounds: diff.any
  }, {
    name: 'edge-distances',
    type: t.edgeDistances,
    triggersBounds: diff.any
  }, {
    name: 'arrow-scale',
    type: t.positiveNumber,
    triggersBounds: diff.any
  }, {
    name: 'loop-direction',
    type: t.angle,
    triggersBounds: diff.any
  }, {
    name: 'loop-sweep',
    type: t.angle,
    triggersBounds: diff.any
  }, {
    name: 'source-distance-from-node',
    type: t.size,
    triggersBounds: diff.any
  }, {
    name: 'target-distance-from-node',
    type: t.size,
    triggersBounds: diff.any
  }];
  var ghost = [{
    name: 'ghost',
    type: t.bool,
    triggersBounds: diff.any
  }, {
    name: 'ghost-offset-x',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'ghost-offset-y',
    type: t.bidirectionalSize,
    triggersBounds: diff.any
  }, {
    name: 'ghost-opacity',
    type: t.zeroOneNumber
  }];
  var core = [{
    name: 'selection-box-color',
    type: t.color
  }, {
    name: 'selection-box-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'selection-box-border-color',
    type: t.color
  }, {
    name: 'selection-box-border-width',
    type: t.size
  }, {
    name: 'active-bg-color',
    type: t.color
  }, {
    name: 'active-bg-opacity',
    type: t.zeroOneNumber
  }, {
    name: 'active-bg-size',
    type: t.size
  }, {
    name: 'outside-texture-bg-color',
    type: t.color
  }, {
    name: 'outside-texture-bg-opacity',
    type: t.zeroOneNumber
  }];

  // pie backgrounds for nodes
  var pie = [];
  styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)
  pie.push({
    name: 'pie-size',
    type: t.sizeMaybePercent
  });
  pie.push({
    name: 'pie-hole',
    type: t.sizeMaybePercent
  });
  pie.push({
    name: 'pie-start-angle',
    type: t.angle
  });
  for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
    pie.push({
      name: 'pie-' + i + '-background-color',
      type: t.color
    });
    pie.push({
      name: 'pie-' + i + '-background-size',
      type: t.percent
    });
    pie.push({
      name: 'pie-' + i + '-background-opacity',
      type: t.zeroOneNumber
    });
  }

  // stripe backgrounds for nodes
  var stripe = [];
  styfn$2.stripeBackgroundN = 16; // because the stripe properties are numbered, give access to a constant N (for renderer use)
  stripe.push({
    name: 'stripe-size',
    type: t.sizeMaybePercent
  });
  stripe.push({
    name: 'stripe-direction',
    type: t.axisDirectionPrimary
  });
  for (var _i = 1; _i <= styfn$2.stripeBackgroundN; _i++) {
    stripe.push({
      name: 'stripe-' + _i + '-background-color',
      type: t.color
    });
    stripe.push({
      name: 'stripe-' + _i + '-background-size',
      type: t.percent
    });
    stripe.push({
      name: 'stripe-' + _i + '-background-opacity',
      type: t.zeroOneNumber
    });
  }

  // edge arrows
  var edgeArrow = [];
  var arrowPrefixes = styfn$2.arrowPrefixes = ['source', 'mid-source', 'target', 'mid-target'];
  [{
    name: 'arrow-shape',
    type: t.arrowShape,
    triggersBounds: diff.any
  }, {
    name: 'arrow-color',
    type: t.color
  }, {
    name: 'arrow-fill',
    type: t.arrowFill
  }, {
    name: 'arrow-width',
    type: t.arrowWidth
  }].forEach(function (prop) {
    arrowPrefixes.forEach(function (prefix) {
      var name = prefix + '-' + prop.name;
      var type = prop.type,
        triggersBounds = prop.triggersBounds;
      edgeArrow.push({
        name: name,
        type: type,
        triggersBounds: triggersBounds
      });
    });
  }, {});
  var props = styfn$2.properties = [].concat(behavior, transition, visibility, overlay, underlay, ghost, commonLabel, labelDimensions, mainLabel, sourceLabel, targetLabel, nodeBody, nodeBorder, nodeOutline, backgroundImage, pie, stripe, compound, edgeLine, edgeArrow, core);
  var propGroups = styfn$2.propertyGroups = {
    // common to all eles
    behavior: behavior,
    transition: transition,
    visibility: visibility,
    overlay: overlay,
    underlay: underlay,
    ghost: ghost,
    // labels
    commonLabel: commonLabel,
    labelDimensions: labelDimensions,
    mainLabel: mainLabel,
    sourceLabel: sourceLabel,
    targetLabel: targetLabel,
    // node props
    nodeBody: nodeBody,
    nodeBorder: nodeBorder,
    nodeOutline: nodeOutline,
    backgroundImage: backgroundImage,
    pie: pie,
    stripe: stripe,
    compound: compound,
    // edge props
    edgeLine: edgeLine,
    edgeArrow: edgeArrow,
    core: core
  };
  var propGroupNames = styfn$2.propertyGroupNames = {};
  var propGroupKeys = styfn$2.propertyGroupKeys = Object.keys(propGroups);
  propGroupKeys.forEach(function (key) {
    propGroupNames[key] = propGroups[key].map(function (prop) {
      return prop.name;
    });
    propGroups[key].forEach(function (prop) {
      return prop.groupKey = key;
    });
  });

  // define aliases
  var aliases = styfn$2.aliases = [{
    name: 'content',
    pointsTo: 'label'
  }, {
    name: 'control-point-distance',
    pointsTo: 'control-point-distances'
  }, {
    name: 'control-point-weight',
    pointsTo: 'control-point-weights'
  }, {
    name: 'segment-distance',
    pointsTo: 'segment-distances'
  }, {
    name: 'segment-weight',
    pointsTo: 'segment-weights'
  }, {
    name: 'segment-radius',
    pointsTo: 'segment-radii'
  }, {
    name: 'edge-text-rotation',
    pointsTo: 'text-rotation'
  }, {
    name: 'padding-left',
    pointsTo: 'padding'
  }, {
    name: 'padding-right',
    pointsTo: 'padding'
  }, {
    name: 'padding-top',
    pointsTo: 'padding'
  }, {
    name: 'padding-bottom',
    pointsTo: 'padding'
  }];

  // list of property names
  styfn$2.propertyNames = props.map(function (p) {
    return p.name;
  });

  // allow access of properties by name ( e.g. style.properties.height )
  for (var _i2 = 0; _i2 < props.length; _i2++) {
    var prop = props[_i2];
    props[prop.name] = prop; // allow lookup by name
  }

  // map aliases
  for (var _i3 = 0; _i3 < aliases.length; _i3++) {
    var alias = aliases[_i3];
    var pointsToProp = props[alias.pointsTo];
    var aliasProp = {
      name: alias.name,
      alias: true,
      pointsTo: pointsToProp
    };

    // add alias prop for parsing
    props.push(aliasProp);
    props[alias.name] = aliasProp; // allow lookup by name
  }
})();
styfn$2.getDefaultProperty = function (name) {
  return this.getDefaultProperties()[name];
};
styfn$2.getDefaultProperties = function () {
  var _p = this._private;
  if (_p.defaultProperties != null) {
    return _p.defaultProperties;
  }
  var rawProps = extend({
    // core props
    'selection-box-color': '#ddd',
    'selection-box-opacity': 0.65,
    'selection-box-border-color': '#aaa',
    'selection-box-border-width': 1,
    'active-bg-color': 'black',
    'active-bg-opacity': 0.15,
    'active-bg-size': 30,
    'outside-texture-bg-color': '#000',
    'outside-texture-bg-opacity': 0.125,
    // common node/edge props
    'events': 'yes',
    'text-events': 'no',
    'text-valign': 'top',
    'text-halign': 'center',
    'text-justification': 'auto',
    'line-height': 1,
    'color': '#000',
    'box-selection': 'contain',
    'text-outline-color': '#000',
    'text-outline-width': 0,
    'text-outline-opacity': 1,
    'text-opacity': 1,
    'text-decoration': 'none',
    'text-transform': 'none',
    'text-wrap': 'none',
    'text-overflow-wrap': 'whitespace',
    'text-max-width': 9999,
    'text-background-color': '#000',
    'text-background-opacity': 0,
    'text-background-shape': 'rectangle',
    'text-background-padding': 0,
    'text-border-opacity': 0,
    'text-border-width': 0,
    'text-border-style': 'solid',
    'text-border-color': '#000',
    'font-family': 'Helvetica Neue, Helvetica, sans-serif',
    'font-style': 'normal',
    'font-weight': 'normal',
    'font-size': 16,
    'min-zoomed-font-size': 0,
    'text-rotation': 'none',
    'source-text-rotation': 'none',
    'target-text-rotation': 'none',
    'visibility': 'visible',
    'display': 'element',
    'opacity': 1,
    'z-compound-depth': 'auto',
    'z-index-compare': 'auto',
    'z-index': 0,
    'label': '',
    'text-margin-x': 0,
    'text-margin-y': 0,
    'source-label': '',
    'source-text-offset': 0,
    'source-text-margin-x': 0,
    'source-text-margin-y': 0,
    'target-label': '',
    'target-text-offset': 0,
    'target-text-margin-x': 0,
    'target-text-margin-y': 0,
    'overlay-opacity': 0,
    'overlay-color': '#000',
    'overlay-padding': 10,
    'overlay-shape': 'round-rectangle',
    'overlay-corner-radius': 'auto',
    'underlay-opacity': 0,
    'underlay-color': '#000',
    'underlay-padding': 10,
    'underlay-shape': 'round-rectangle',
    'underlay-corner-radius': 'auto',
    'transition-property': 'none',
    'transition-duration': 0,
    'transition-delay': 0,
    'transition-timing-function': 'linear',
    'box-select-labels': 'no',
    // node props
    'background-blacken': 0,
    'background-color': '#999',
    'background-fill': 'solid',
    'background-opacity': 1,
    'background-image': 'none',
    'background-image-crossorigin': 'anonymous',
    'background-image-opacity': 1,
    'background-image-containment': 'inside',
    'background-image-smoothing': 'yes',
    'background-position-x': '50%',
    'background-position-y': '50%',
    'background-offset-x': 0,
    'background-offset-y': 0,
    'background-width-relative-to': 'include-padding',
    'background-height-relative-to': 'include-padding',
    'background-repeat': 'no-repeat',
    'background-fit': 'none',
    'background-clip': 'node',
    'background-width': 'auto',
    'background-height': 'auto',
    'border-color': '#000',
    'border-opacity': 1,
    'border-width': 0,
    'border-style': 'solid',
    'border-dash-pattern': [4, 2],
    'border-dash-offset': 0,
    'border-cap': 'butt',
    'border-join': 'miter',
    'border-position': 'center',
    'outline-color': '#999',
    'outline-opacity': 1,
    'outline-width': 0,
    'outline-offset': 0,
    'outline-style': 'solid',
    'height': 30,
    'width': 30,
    'shape': 'ellipse',
    'shape-polygon-points': '-1, -1,   1, -1,   1, 1,   -1, 1',
    'corner-radius': 'auto',
    'bounds-expansion': 0,
    // node gradient
    'background-gradient-direction': 'to-bottom',
    'background-gradient-stop-colors': '#999',
    'background-gradient-stop-positions': '0%',
    // ghost props
    'ghost': 'no',
    'ghost-offset-y': 0,
    'ghost-offset-x': 0,
    'ghost-opacity': 0,
    // compound props
    'padding': 0,
    'padding-relative-to': 'width',
    'position': 'origin',
    'compound-sizing-wrt-labels': 'include',
    'min-width': 0,
    'min-width-bias-left': 0,
    'min-width-bias-right': 0,
    'min-height': 0,
    'min-height-bias-top': 0,
    'min-height-bias-bottom': 0
  }, {
    // node pie bg
    'pie-size': '100%',
    'pie-hole': 0,
    'pie-start-angle': '0deg'
  }, [{
    name: 'pie-{{i}}-background-color',
    value: 'black'
  }, {
    name: 'pie-{{i}}-background-size',
    value: '0%'
  }, {
    name: 'pie-{{i}}-background-opacity',
    value: 1
  }].reduce(function (css, prop) {
    for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
      var name = prop.name.replace('{{i}}', i);
      var val = prop.value;
      css[name] = val;
    }
    return css;
  }, {}), {
    // node stripes bg
    'stripe-size': '100%',
    'stripe-direction': 'horizontal'
  }, [{
    name: 'stripe-{{i}}-background-color',
    value: 'black'
  }, {
    name: 'stripe-{{i}}-background-size',
    value: '0%'
  }, {
    name: 'stripe-{{i}}-background-opacity',
    value: 1
  }].reduce(function (css, prop) {
    for (var i = 1; i <= styfn$2.stripeBackgroundN; i++) {
      var name = prop.name.replace('{{i}}', i);
      var val = prop.value;
      css[name] = val;
    }
    return css;
  }, {}), {
    // edge props
    'line-style': 'solid',
    'line-color': '#999',
    'line-fill': 'solid',
    'line-cap': 'butt',
    'line-opacity': 1,
    'line-outline-width': 0,
    'line-outline-color': '#000',
    'line-gradient-stop-colors': '#999',
    'line-gradient-stop-positions': '0%',
    'control-point-step-size': 40,
    'control-point-weights': 0.5,
    'segment-weights': 0.5,
    'segment-distances': 20,
    'segment-radii': 15,
    'radius-type': 'arc-radius',
    'taxi-turn': '50%',
    'taxi-radius': 15,
    'taxi-turn-min-distance': 10,
    'taxi-direction': 'auto',
    'edge-distances': 'intersection',
    'curve-style': 'haystack',
    'haystack-radius': 0,
    'arrow-scale': 1,
    'loop-direction': '-45deg',
    'loop-sweep': '-90deg',
    'source-distance-from-node': 0,
    'target-distance-from-node': 0,
    'source-endpoint': 'outside-to-node',
    'target-endpoint': 'outside-to-node',
    'line-dash-pattern': [6, 3],
    'line-dash-offset': 0
  }, [{
    name: 'arrow-shape',
    value: 'none'
  }, {
    name: 'arrow-color',
    value: '#999'
  }, {
    name: 'arrow-fill',
    value: 'filled'
  }, {
    name: 'arrow-width',
    value: 1
  }].reduce(function (css, prop) {
    styfn$2.arrowPrefixes.forEach(function (prefix) {
      var name = prefix + '-' + prop.name;
      var val = prop.value;
      css[name] = val;
    });
    return css;
  }, {}));
  var parsedProps = {};
  for (var i = 0; i < this.properties.length; i++) {
    var prop = this.properties[i];
    if (prop.pointsTo) {
      continue;
    }
    var name = prop.name;
    var val = rawProps[name];
    var parsedProp = this.parse(name, val);
    parsedProps[name] = parsedProp;
  }
  _p.defaultProperties = parsedProps;
  return _p.defaultProperties;
};
styfn$2.addDefaultStylesheet = function () {
  this.selector(':parent').css({
    'shape': 'rectangle',
    'padding': 10,
    'background-color': '#eee',
    'border-color': '#ccc',
    'border-width': 1
  }).selector('edge').css({
    'width': 3
  }).selector(':loop').css({
    'curve-style': 'bezier'
  }).selector('edge:compound').css({
    'curve-style': 'bezier',
    'source-endpoint': 'outside-to-line',
    'target-endpoint': 'outside-to-line'
  }).selector(':selected').css({
    'background-color': '#0169D9',
    'line-color': '#0169D9',
    'source-arrow-color': '#0169D9',
    'target-arrow-color': '#0169D9',
    'mid-source-arrow-color': '#0169D9',
    'mid-target-arrow-color': '#0169D9'
  }).selector(':parent:selected').css({
    'background-color': '#CCE1F9',
    'border-color': '#aec8e5'
  }).selector(':active').css({
    'overlay-color': 'black',
    'overlay-padding': 10,
    'overlay-opacity': 0.25
  });
  this.defaultLength = this.length;
};

var styfn$1 = {};

// a caching layer for property parsing
styfn$1.parse = function (name, value, propIsBypass, propIsFlat) {
  var self = this;

  // function values can't be cached in all cases, and there isn't much benefit of caching them anyway
  if (fn$6(value)) {
    return self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  }
  var flatKey = propIsFlat === 'mapping' || propIsFlat === true || propIsFlat === false || propIsFlat == null ? 'dontcare' : propIsFlat;
  var bypassKey = propIsBypass ? 't' : 'f';
  var valueKey = '' + value;
  var argHash = hashStrings(name, valueKey, bypassKey, flatKey);
  var propCache = self.propCache = self.propCache || [];
  var ret;
  if (!(ret = propCache[argHash])) {
    ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  }

  // - bypasses can't be shared b/c the value can be changed by animations or otherwise overridden
  // - mappings can't be shared b/c mappings are per-element
  if (propIsBypass || propIsFlat === 'mapping') {
    // need a copy since props are mutated later in their lifecycles
    ret = copy(ret);
    if (ret) {
      ret.value = copy(ret.value); // because it could be an array, e.g. colour
    }
  }
  return ret;
};
styfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {
  var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);
  if (!prop && value != null) {
    warn("The style property `".concat(name, ": ").concat(value, "` is invalid"));
  }
  if (prop && (prop.name === 'width' || prop.name === 'height') && value === 'label') {
    warn('The style value of `label` is deprecated for `' + prop.name + '`');
  }
  return prop;
};

// parse a property; return null on invalid; return parsed property otherwise
// fields :
// - name : the name of the property
// - value : the parsed, native-typed value of the property
// - strValue : a string value that represents the property value in valid css
// - bypass : true iff the property is a bypass property
styfn$1.parseImpl = function (name, value, propIsBypass, propIsFlat) {
  var self = this;
  name = camel2dash(name); // make sure the property name is in dash form (e.g. 'property-name' not 'propertyName')

  var property = self.properties[name];
  var passedValue = value;
  var types = self.types;
  if (!property) {
    return null;
  } // return null on property of unknown name
  if (value === undefined) {
    return null;
  } // can't assign undefined

  // the property may be an alias
  if (property.alias) {
    property = property.pointsTo;
    name = property.name;
  }
  var valueIsString = string(value);
  if (valueIsString) {
    // trim the value to make parsing easier
    value = value.trim();
  }
  var type = property.type;
  if (!type) {
    return null;
  } // no type, no luck

  // check if bypass is null or empty string (i.e. indication to delete bypass property)
  if (propIsBypass && (value === '' || value === null)) {
    return {
      name: name,
      value: value,
      bypass: true,
      deleteBypass: true
    };
  }

  // check if value is a function used as a mapper
  if (fn$6(value)) {
    return {
      name: name,
      value: value,
      strValue: 'fn',
      mapped: types.fn,
      bypass: propIsBypass
    };
  }

  // check if value is mapped
  var data, mapData;
  if (!valueIsString || propIsFlat || value.length < 7 || value[1] !== 'a') ; else if (value.length >= 7 && value[0] === 'd' && (data = new RegExp(types.data.regex).exec(value))) {
    if (propIsBypass) {
      return false;
    } // mappers not allowed in bypass

    var mapped = types.data;
    return {
      name: name,
      value: data,
      strValue: '' + value,
      mapped: mapped,
      field: data[1],
      bypass: propIsBypass
    };
  } else if (value.length >= 10 && value[0] === 'm' && (mapData = new RegExp(types.mapData.regex).exec(value))) {
    if (propIsBypass) {
      return false;
    } // mappers not allowed in bypass
    if (type.multiple) {
      return false;
    } // impossible to map to num

    var _mapped = types.mapData;

    // we can map only if the type is a colour or a number
    if (!(type.color || type.number)) {
      return false;
    }
    var valueMin = this.parse(name, mapData[4]); // parse to validate
    if (!valueMin || valueMin.mapped) {
      return false;
    } // can't be invalid or mapped

    var valueMax = this.parse(name, mapData[5]); // parse to validate
    if (!valueMax || valueMax.mapped) {
      return false;
    } // can't be invalid or mapped

    // check if valueMin and valueMax are the same
    if (valueMin.pfValue === valueMax.pfValue || valueMin.strValue === valueMax.strValue) {
      warn('`' + name + ': ' + value + '` is not a valid mapper because the output range is zero; converting to `' + name + ': ' + valueMin.strValue + '`');
      return this.parse(name, valueMin.strValue); // can't make much of a mapper without a range
    } else if (type.color) {
      var c1 = valueMin.value;
      var c2 = valueMax.value;
      var same = c1[0] === c2[0] // red
      && c1[1] === c2[1] // green
      && c1[2] === c2[2] // blue
      && (
      // optional alpha
      c1[3] === c2[3] // same alpha outright
      || (c1[3] == null || c1[3] === 1 // full opacity for colour 1?
      ) && (c2[3] == null || c2[3] === 1) // full opacity for colour 2?
      );
      if (same) {
        return false;
      } // can't make a mapper without a range
    }
    return {
      name: name,
      value: mapData,
      strValue: '' + value,
      mapped: _mapped,
      field: mapData[1],
      fieldMin: parseFloat(mapData[2]),
      // min & max are numeric
      fieldMax: parseFloat(mapData[3]),
      valueMin: valueMin.value,
      valueMax: valueMax.value,
      bypass: propIsBypass
    };
  }
  if (type.multiple && propIsFlat !== 'multiple') {
    var vals;
    if (valueIsString) {
      vals = value.split(/\s+/);
    } else if (array(value)) {
      vals = value;
    } else {
      vals = [value];
    }
    if (type.evenMultiple && vals.length % 2 !== 0) {
      return null;
    }
    var valArr = [];
    var unitsArr = [];
    var pfValArr = [];
    var strVal = '';
    var hasEnum = false;
    for (var i = 0; i < vals.length; i++) {
      var p = self.parse(name, vals[i], propIsBypass, 'multiple');
      hasEnum = hasEnum || string(p.value);
      valArr.push(p.value);
      pfValArr.push(p.pfValue != null ? p.pfValue : p.value);
      unitsArr.push(p.units);
      strVal += (i > 0 ? ' ' : '') + p.strValue;
    }
    if (type.validate && !type.validate(valArr, unitsArr)) {
      return null;
    }
    if (type.singleEnum && hasEnum) {
      if (valArr.length === 1 && string(valArr[0])) {
        return {
          name: name,
          value: valArr[0],
          strValue: valArr[0],
          bypass: propIsBypass
        };
      } else {
        return null;
      }
    }
    return {
      name: name,
      value: valArr,
      pfValue: pfValArr,
      strValue: strVal,
      bypass: propIsBypass,
      units: unitsArr
    };
  }

  // several types also allow enums
  var checkEnums = function checkEnums() {
    for (var _i = 0; _i < type.enums.length; _i++) {
      var en = type.enums[_i];
      if (en === value) {
        return {
          name: name,
          value: value,
          strValue: '' + value,
          bypass: propIsBypass
        };
      }
    }
    return null;
  };

  // check the type and return the appropriate object
  if (type.number) {
    var units;
    var implicitUnits = 'px'; // not set => px

    if (type.units) {
      // use specified units if set
      units = type.units;
    }
    if (type.implicitUnits) {
      implicitUnits = type.implicitUnits;
    }
    if (!type.unitless) {
      if (valueIsString) {
        var unitsRegex = 'px|em' + (type.allowPercent ? '|\\%' : '');
        if (units) {
          unitsRegex = units;
        } // only allow explicit units if so set
        var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');
        if (match) {
          value = match[1];
          units = match[2] || implicitUnits;
        }
      } else if (!units || type.implicitUnits) {
        units = implicitUnits; // implicitly px if unspecified
      }
    }
    value = parseFloat(value);

    // if not a number and enums not allowed, then the value is invalid
    if (isNaN(value) && type.enums === undefined) {
      return null;
    }

    // check if this number type also accepts special keywords in place of numbers
    // (i.e. `left`, `auto`, etc)
    if (isNaN(value) && type.enums !== undefined) {
      value = passedValue;
      return checkEnums();
    }

    // check if value must be an integer
    if (type.integer && !integer(value)) {
      return null;
    }

    // check value is within range
    if (type.min !== undefined && (value < type.min || type.strictMin && value === type.min) || type.max !== undefined && (value > type.max || type.strictMax && value === type.max)) {
      return null;
    }
    var ret = {
      name: name,
      value: value,
      strValue: '' + value + (units ? units : ''),
      units: units,
      bypass: propIsBypass
    };

    // normalise value in pixels
    if (type.unitless || units !== 'px' && units !== 'em') {
      ret.pfValue = value;
    } else {
      ret.pfValue = units === 'px' || !units ? value : this.getEmSizeInPixels() * value;
    }

    // normalise value in ms
    if (units === 'ms' || units === 's') {
      ret.pfValue = units === 'ms' ? value : 1000 * value;
    }

    // normalise value in rad
    if (units === 'deg' || units === 'rad') {
      ret.pfValue = units === 'rad' ? value : deg2rad(value);
    }

    // normalize value in %
    if (units === '%') {
      ret.pfValue = value / 100;
    }
    return ret;
  } else if (type.propList) {
    var props = [];
    var propsStr = '' + value;
    if (propsStr === 'none') ; else {
      // go over each prop

      var propsSplit = propsStr.split(/\s*,\s*|\s+/);
      for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {
        var propName = propsSplit[_i2].trim();
        if (self.properties[propName]) {
          props.push(propName);
        } else {
          warn('`' + propName + '` is not a valid property name');
        }
      }
      if (props.length === 0) {
        return null;
      }
    }
    return {
      name: name,
      value: props,
      strValue: props.length === 0 ? 'none' : props.join(' '),
      bypass: propIsBypass
    };
  } else if (type.color) {
    var tuple = color2tuple(value);
    if (!tuple) {
      return null;
    }
    return {
      name: name,
      value: tuple,
      pfValue: tuple,
      strValue: 'rgb(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')',
      // n.b. no spaces b/c of multiple support
      bypass: propIsBypass
    };
  } else if (type.regex || type.regexes) {
    // first check enums
    if (type.enums) {
      var enumProp = checkEnums();
      if (enumProp) {
        return enumProp;
      }
    }
    var regexes = type.regexes ? type.regexes : [type.regex];
    for (var _i3 = 0; _i3 < regexes.length; _i3++) {
      var regex = new RegExp(regexes[_i3]); // make a regex from the type string
      var m = regex.exec(value);
      if (m) {
        // regex matches
        return {
          name: name,
          value: type.singleRegexMatchValue ? m[1] : m,
          strValue: '' + value,
          bypass: propIsBypass
        };
      }
    }
    return null; // didn't match any
  } else if (type.string) {
    // just return
    return {
      name: name,
      value: '' + value,
      strValue: '' + value,
      bypass: propIsBypass
    };
  } else if (type.enums) {
    // check enums last because it's a combo type in others
    return checkEnums();
  } else {
    return null; // not a type we can handle
  }
};

var _Style = function Style(cy) {
  if (!(this instanceof _Style)) {
    return new _Style(cy);
  }
  if (!core(cy)) {
    error('A style must have a core reference');
    return;
  }
  this._private = {
    cy: cy,
    coreStyle: {}
  };
  this.length = 0;
  this.resetToDefault();
};
var styfn = _Style.prototype;
styfn.instanceString = function () {
  return 'style';
};

// remove all contexts
styfn.clear = function () {
  var _p = this._private;
  var cy = _p.cy;
  var eles = cy.elements();
  for (var i = 0; i < this.length; i++) {
    this[i] = undefined;
  }
  this.length = 0;
  _p.contextStyles = {};
  _p.propDiffs = {};
  this.cleanElements(eles, true);
  eles.forEach(function (ele) {
    var ele_p = ele[0]._private;
    ele_p.styleDirty = true;
    ele_p.appliedInitStyle = false;
  });
  return this; // chaining
};
styfn.resetToDefault = function () {
  this.clear();
  this.addDefaultStylesheet();
  return this;
};

// builds a style object for the 'core' selector
styfn.core = function (propName) {
  return this._private.coreStyle[propName] || this.getDefaultProperty(propName);
};

// create a new context from the specified selector string and switch to that context
styfn.selector = function (selectorStr) {
  // 'core' is a special case and does not need a selector
  var selector = selectorStr === 'core' ? null : new Selector(selectorStr);
  var i = this.length++; // new context means new index
  this[i] = {
    selector: selector,
    properties: [],
    mappedProperties: [],
    index: i
  };
  return this; // chaining
};

// add one or many css rules to the current context
styfn.css = function () {
  var self = this;
  var args = arguments;
  if (args.length === 1) {
    var map = args[0];
    for (var i = 0; i < self.properties.length; i++) {
      var prop = self.properties[i];
      var mapVal = map[prop.name];
      if (mapVal === undefined) {
        mapVal = map[dash2camel(prop.name)];
      }
      if (mapVal !== undefined) {
        this.cssRule(prop.name, mapVal);
      }
    }
  } else if (args.length === 2) {
    this.cssRule(args[0], args[1]);
  }

  // do nothing if args are invalid

  return this; // chaining
};
styfn.style = styfn.css;

// add a single css rule to the current context
styfn.cssRule = function (name, value) {
  // name-value pair
  var property = this.parse(name, value);

  // add property to current context if valid
  if (property) {
    var i = this.length - 1;
    this[i].properties.push(property);
    this[i].properties[property.name] = property; // allow access by name as well

    if (property.name.match(/pie-(\d+)-background-size/) && property.value) {
      this._private.hasPie = true;
    }
    if (property.name.match(/stripe-(\d+)-background-size/) && property.value) {
      this._private.hasStripe = true;
    }
    if (property.mapped) {
      this[i].mappedProperties.push(property);
    }

    // add to core style if necessary
    var currentSelectorIsCore = !this[i].selector;
    if (currentSelectorIsCore) {
      this._private.coreStyle[property.name] = property;
    }
  }
  return this; // chaining
};
styfn.append = function (style) {
  if (stylesheet(style)) {
    style.appendToStyle(this);
  } else if (array(style)) {
    this.appendFromJson(style);
  } else if (string(style)) {
    this.appendFromString(style);
  } // you probably wouldn't want to append a Style, since you'd duplicate the default parts

  return this;
};

// static function
_Style.fromJson = function (cy, json) {
  var style = new _Style(cy);
  style.fromJson(json);
  return style;
};
_Style.fromString = function (cy, string) {
  return new _Style(cy).fromString(string);
};
[styfn$8, styfn$7, styfn$6, styfn$5, styfn$4, styfn$3, styfn$2, styfn$1].forEach(function (props) {
  extend(styfn, props);
});
_Style.types = styfn.types;
_Style.properties = styfn.properties;
_Style.propertyGroups = styfn.propertyGroups;
_Style.propertyGroupNames = styfn.propertyGroupNames;
_Style.propertyGroupKeys = styfn.propertyGroupKeys;

var corefn$2 = {
  style: function style(newStyle) {
    if (newStyle) {
      var s = this.setStyle(newStyle);
      s.update();
    }
    return this._private.style;
  },
  setStyle: function setStyle(style) {
    var _p = this._private;
    if (stylesheet(style)) {
      _p.style = style.generateStyle(this);
    } else if (array(style)) {
      _p.style = _Style.fromJson(this, style);
    } else if (string(style)) {
      _p.style = _Style.fromString(this, style);
    } else {
      _p.style = _Style(this);
    }
    return _p.style;
  },
  // e.g. cy.data() changed => recalc ele mappers
  updateStyle: function updateStyle() {
    this.mutableElements().updateStyle(); // just send to all eles
  }
};

var defaultSelectionType = 'single';
var corefn$1 = {
  autolock: function autolock(bool) {
    if (bool !== undefined) {
      this._private.autolock = bool ? true : false;
    } else {
      return this._private.autolock;
    }
    return this; // chaining
  },
  autoungrabify: function autoungrabify(bool) {
    if (bool !== undefined) {
      this._private.autoungrabify = bool ? true : false;
    } else {
      return this._private.autoungrabify;
    }
    return this; // chaining
  },
  autounselectify: function autounselectify(bool) {
    if (bool !== undefined) {
      this._private.autounselectify = bool ? true : false;
    } else {
      return this._private.autounselectify;
    }
    return this; // chaining
  },
  selectionType: function selectionType(selType) {
    var _p = this._private;
    if (_p.selectionType == null) {
      _p.selectionType = defaultSelectionType;
    }
    if (selType !== undefined) {
      if (selType === 'additive' || selType === 'single') {
        _p.selectionType = selType;
      }
    } else {
      return _p.selectionType;
    }
    return this;
  },
  panningEnabled: function panningEnabled(bool) {
    if (bool !== undefined) {
      this._private.panningEnabled = bool ? true : false;
    } else {
      return this._private.panningEnabled;
    }
    return this; // chaining
  },
  userPanningEnabled: function userPanningEnabled(bool) {
    if (bool !== undefined) {
      this._private.userPanningEnabled = bool ? true : false;
    } else {
      return this._private.userPanningEnabled;
    }
    return this; // chaining
  },
  zoomingEnabled: function zoomingEnabled(bool) {
    if (bool !== undefined) {
      this._private.zoomingEnabled = bool ? true : false;
    } else {
      return this._private.zoomingEnabled;
    }
    return this; // chaining
  },
  userZoomingEnabled: function userZoomingEnabled(bool) {
    if (bool !== undefined) {
      this._private.userZoomingEnabled = bool ? true : false;
    } else {
      return this._private.userZoomingEnabled;
    }
    return this; // chaining
  },
  boxSelectionEnabled: function boxSelectionEnabled(bool) {
    if (bool !== undefined) {
      this._private.boxSelectionEnabled = bool ? true : false;
    } else {
      return this._private.boxSelectionEnabled;
    }
    return this; // chaining
  },
  pan: function pan() {
    var args = arguments;
    var pan = this._private.pan;
    var dim, val, dims, x, y;
    switch (args.length) {
      case 0:
        // .pan()
        return pan;
      case 1:
        if (string(args[0])) {
          // .pan('x')
          dim = args[0];
          return pan[dim];
        } else if (plainObject(args[0])) {
          // .pan({ x: 0, y: 100 })
          if (!this._private.panningEnabled) {
            return this;
          }
          dims = args[0];
          x = dims.x;
          y = dims.y;
          if (number$1(x)) {
            pan.x = x;
          }
          if (number$1(y)) {
            pan.y = y;
          }
          this.emit('pan viewport');
        }
        break;
      case 2:
        // .pan('x', 100)
        if (!this._private.panningEnabled) {
          return this;
        }
        dim = args[0];
        val = args[1];
        if ((dim === 'x' || dim === 'y') && number$1(val)) {
          pan[dim] = val;
        }
        this.emit('pan viewport');
        break;
      // invalid
    }
    this.notify('viewport');
    return this; // chaining
  },
  panBy: function panBy(arg0, arg1) {
    var args = arguments;
    var pan = this._private.pan;
    var dim, val, dims, x, y;
    if (!this._private.panningEnabled) {
      return this;
    }
    switch (args.length) {
      case 1:
        if (plainObject(arg0)) {
          // .panBy({ x: 0, y: 100 })
          dims = args[0];
          x = dims.x;
          y = dims.y;
          if (number$1(x)) {
            pan.x += x;
          }
          if (number$1(y)) {
            pan.y += y;
          }
          this.emit('pan viewport');
        }
        break;
      case 2:
        // .panBy('x', 100)
        dim = arg0;
        val = arg1;
        if ((dim === 'x' || dim === 'y') && number$1(val)) {
          pan[dim] += val;
        }
        this.emit('pan viewport');
        break;
      // invalid
    }
    this.notify('viewport');
    return this; // chaining
  },
  gc: function gc() {
    this.notify('gc');
  },
  fit: function fit(elements, padding) {
    var viewportState = this.getFitViewport(elements, padding);
    if (viewportState) {
      var _p = this._private;
      _p.zoom = viewportState.zoom;
      _p.pan = viewportState.pan;
      this.emit('pan zoom viewport');
      this.notify('viewport');
    }
    return this; // chaining
  },
  getFitViewport: function getFitViewport(elements, padding) {
    if (number$1(elements) && padding === undefined) {
      // elements is optional
      padding = elements;
      elements = undefined;
    }
    if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
      return;
    }
    var bb;
    if (string(elements)) {
      var sel = elements;
      elements = this.$(sel);
    } else if (boundingBox(elements)) {
      // assume bb
      var bbe = elements;
      bb = {
        x1: bbe.x1,
        y1: bbe.y1,
        x2: bbe.x2,
        y2: bbe.y2
      };
      bb.w = bb.x2 - bb.x1;
      bb.h = bb.y2 - bb.y1;
    } else if (!elementOrCollection(elements)) {
      elements = this.mutableElements();
    }
    if (elementOrCollection(elements) && elements.empty()) {
      return;
    } // can't fit to nothing

    bb = bb || elements.boundingBox();
    var w = this.width();
    var h = this.height();
    var zoom;
    padding = number$1(padding) ? padding : 0;
    if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0 && !isNaN(bb.w) && !isNaN(bb.h) && bb.w > 0 && bb.h > 0) {
      zoom = Math.min((w - 2 * padding) / bb.w, (h - 2 * padding) / bb.h);

      // crop zoom
      zoom = zoom > this._private.maxZoom ? this._private.maxZoom : zoom;
      zoom = zoom < this._private.minZoom ? this._private.minZoom : zoom;
      var pan = {
        // now pan to middle
        x: (w - zoom * (bb.x1 + bb.x2)) / 2,
        y: (h - zoom * (bb.y1 + bb.y2)) / 2
      };
      return {
        zoom: zoom,
        pan: pan
      };
    }
    return;
  },
  zoomRange: function zoomRange(min, max) {
    var _p = this._private;
    if (max == null) {
      var opts = min;
      min = opts.min;
      max = opts.max;
    }
    if (number$1(min) && number$1(max) && min <= max) {
      _p.minZoom = min;
      _p.maxZoom = max;
    } else if (number$1(min) && max === undefined && min <= _p.maxZoom) {
      _p.minZoom = min;
    } else if (number$1(max) && min === undefined && max >= _p.minZoom) {
      _p.maxZoom = max;
    }
    return this;
  },
  minZoom: function minZoom(zoom) {
    if (zoom === undefined) {
      return this._private.minZoom;
    } else {
      return this.zoomRange({
        min: zoom
      });
    }
  },
  maxZoom: function maxZoom(zoom) {
    if (zoom === undefined) {
      return this._private.maxZoom;
    } else {
      return this.zoomRange({
        max: zoom
      });
    }
  },
  getZoomedViewport: function getZoomedViewport(params) {
    var _p = this._private;
    var currentPan = _p.pan;
    var currentZoom = _p.zoom;
    var pos; // in rendered px
    var zoom;
    var bail = false;
    if (!_p.zoomingEnabled) {
      // zooming disabled
      bail = true;
    }
    if (number$1(params)) {
      // then set the zoom
      zoom = params;
    } else if (plainObject(params)) {
      // then zoom about a point
      zoom = params.level;
      if (params.position != null) {
        pos = modelToRenderedPosition$1(params.position, currentZoom, currentPan);
      } else if (params.renderedPosition != null) {
        pos = params.renderedPosition;
      }
      if (pos != null && !_p.panningEnabled) {
        // panning disabled
        bail = true;
      }
    }

    // crop zoom
    zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;
    zoom = zoom < _p.minZoom ? _p.minZoom : zoom;

    // can't zoom with invalid params
    if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {
      return null;
    }
    if (pos != null) {
      // set zoom about position
      var pan1 = currentPan;
      var zoom1 = currentZoom;
      var zoom2 = zoom;
      var pan2 = {
        x: -zoom2 / zoom1 * (pos.x - pan1.x) + pos.x,
        y: -zoom2 / zoom1 * (pos.y - pan1.y) + pos.y
      };
      return {
        zoomed: true,
        panned: true,
        zoom: zoom2,
        pan: pan2
      };
    } else {
      // just set the zoom
      return {
        zoomed: true,
        panned: false,
        zoom: zoom,
        pan: currentPan
      };
    }
  },
  zoom: function zoom(params) {
    if (params === undefined) {
      // get
      return this._private.zoom;
    } else {
      // set
      var vp = this.getZoomedViewport(params);
      var _p = this._private;
      if (vp == null || !vp.zoomed) {
        return this;
      }
      _p.zoom = vp.zoom;
      if (vp.panned) {
        _p.pan.x = vp.pan.x;
        _p.pan.y = vp.pan.y;
      }
      this.emit('zoom' + (vp.panned ? ' pan' : '') + ' viewport');
      this.notify('viewport');
      return this; // chaining
    }
  },
  viewport: function viewport(opts) {
    var _p = this._private;
    var zoomDefd = true;
    var panDefd = true;
    var events = []; // to trigger
    var zoomFailed = false;
    var panFailed = false;
    if (!opts) {
      return this;
    }
    if (!number$1(opts.zoom)) {
      zoomDefd = false;
    }
    if (!plainObject(opts.pan)) {
      panDefd = false;
    }
    if (!zoomDefd && !panDefd) {
      return this;
    }
    if (zoomDefd) {
      var z = opts.zoom;
      if (z < _p.minZoom || z > _p.maxZoom || !_p.zoomingEnabled) {
        zoomFailed = true;
      } else {
        _p.zoom = z;
        events.push('zoom');
      }
    }
    if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {
      var p = opts.pan;
      if (number$1(p.x)) {
        _p.pan.x = p.x;
        panFailed = false;
      }
      if (number$1(p.y)) {
        _p.pan.y = p.y;
        panFailed = false;
      }
      if (!panFailed) {
        events.push('pan');
      }
    }
    if (events.length > 0) {
      events.push('viewport');
      this.emit(events.join(' '));
      this.notify('viewport');
    }
    return this; // chaining
  },
  center: function center(elements) {
    var pan = this.getCenterPan(elements);
    if (pan) {
      this._private.pan = pan;
      this.emit('pan viewport');
      this.notify('viewport');
    }
    return this; // chaining
  },
  getCenterPan: function getCenterPan(elements, zoom) {
    if (!this._private.panningEnabled) {
      return;
    }
    if (string(elements)) {
      var selector = elements;
      elements = this.mutableElements().filter(selector);
    } else if (!elementOrCollection(elements)) {
      elements = this.mutableElements();
    }
    if (elements.length === 0) {
      return;
    } // can't centre pan to nothing

    var bb = elements.boundingBox();
    var w = this.width();
    var h = this.height();
    zoom = zoom === undefined ? this._private.zoom : zoom;
    var pan = {
      // middle
      x: (w - zoom * (bb.x1 + bb.x2)) / 2,
      y: (h - zoom * (bb.y1 + bb.y2)) / 2
    };
    return pan;
  },
  reset: function reset() {
    if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
      return this;
    }
    this.viewport({
      pan: {
        x: 0,
        y: 0
      },
      zoom: 1
    });
    return this; // chaining
  },
  invalidateSize: function invalidateSize() {
    this._private.sizeCache = null;
  },
  size: function size() {
    var _p = this._private;
    var container = _p.container;
    var cy = this;
    return _p.sizeCache = _p.sizeCache || (container ? function () {
      var style = cy.window().getComputedStyle(container);
      var val = function val(name) {
        return parseFloat(style.getPropertyValue(name));
      };
      return {
        width: container.clientWidth - val('padding-left') - val('padding-right'),
        height: container.clientHeight - val('padding-top') - val('padding-bottom')
      };
    }() : {
      // fallback if no container (not 0 b/c can be used for dividing etc)
      width: 1,
      height: 1
    });
  },
  width: function width() {
    return this.size().width;
  },
  height: function height() {
    return this.size().height;
  },
  extent: function extent() {
    var pan = this._private.pan;
    var zoom = this._private.zoom;
    var rb = this.renderedExtent();
    var b = {
      x1: (rb.x1 - pan.x) / zoom,
      x2: (rb.x2 - pan.x) / zoom,
      y1: (rb.y1 - pan.y) / zoom,
      y2: (rb.y2 - pan.y) / zoom
    };
    b.w = b.x2 - b.x1;
    b.h = b.y2 - b.y1;
    return b;
  },
  renderedExtent: function renderedExtent() {
    var width = this.width();
    var height = this.height();
    return {
      x1: 0,
      y1: 0,
      x2: width,
      y2: height,
      w: width,
      h: height
    };
  },
  multiClickDebounceTime: function multiClickDebounceTime(_int) {
    if (_int) this._private.multiClickDebounceTime = _int;else return this._private.multiClickDebounceTime;
    return this; // chaining
  }
};

// aliases
corefn$1.centre = corefn$1.center;

// backwards compatibility
corefn$1.autolockNodes = corefn$1.autolock;
corefn$1.autoungrabifyNodes = corefn$1.autoungrabify;

var fn = {
  data: define.data({
    field: 'data',
    bindingEvent: 'data',
    allowBinding: true,
    allowSetting: true,
    settingEvent: 'data',
    settingTriggersEvent: true,
    triggerFnName: 'trigger',
    allowGetting: true,
    updateStyle: true
  }),
  removeData: define.removeData({
    field: 'data',
    event: 'data',
    triggerFnName: 'trigger',
    triggerEvent: true,
    updateStyle: true
  }),
  scratch: define.data({
    field: 'scratch',
    bindingEvent: 'scratch',
    allowBinding: true,
    allowSetting: true,
    settingEvent: 'scratch',
    settingTriggersEvent: true,
    triggerFnName: 'trigger',
    allowGetting: true,
    updateStyle: true
  }),
  removeScratch: define.removeData({
    field: 'scratch',
    event: 'scratch',
    triggerFnName: 'trigger',
    triggerEvent: true,
    updateStyle: true
  })
};

// aliases
fn.attr = fn.data;
fn.removeAttr = fn.removeData;

var Core = function Core(opts) {
  var cy = this;
  opts = extend({}, opts);
  var container = opts.container;

  // allow for passing a wrapped jquery object
  // e.g. cytoscape({ container: $('#cy') })
  if (container && !htmlElement(container) && htmlElement(container[0])) {
    container = container[0];
  }
  var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery
  reg = reg || {};
  if (reg && reg.cy) {
    reg.cy.destroy();
    reg = {}; // old instance => replace reg completely
  }
  var readies = reg.readies = reg.readies || [];
  if (container) {
    container._cyreg = reg;
  } // make sure container assoc'd reg points to this cy
  reg.cy = cy;
  var head = _window !== undefined && container !== undefined && !opts.headless;
  var options = opts;
  options.layout = extend({
    name: head ? 'grid' : 'null'
  }, options.layout);
  options.renderer = extend({
    name: head ? 'canvas' : 'null'
  }, options.renderer);
  var defVal = function defVal(def, val, altVal) {
    if (val !== undefined) {
      return val;
    } else if (altVal !== undefined) {
      return altVal;
    } else {
      return def;
    }
  };
  var _p = this._private = {
    container: container,
    // html dom ele container
    ready: false,
    // whether ready has been triggered
    options: options,
    // cached options
    elements: new Collection(this),
    // elements in the graph
    listeners: [],
    // list of listeners
    aniEles: new Collection(this),
    // elements being animated
    data: options.data || {},
    // data for the core
    scratch: {},
    // scratch object for core
    layout: null,
    renderer: null,
    destroyed: false,
    // whether destroy was called
    notificationsEnabled: true,
    // whether notifications are sent to the renderer
    minZoom: 1e-50,
    maxZoom: 1e50,
    zoomingEnabled: defVal(true, options.zoomingEnabled),
    userZoomingEnabled: defVal(true, options.userZoomingEnabled),
    panningEnabled: defVal(true, options.panningEnabled),
    userPanningEnabled: defVal(true, options.userPanningEnabled),
    boxSelectionEnabled: defVal(true, options.boxSelectionEnabled),
    autolock: defVal(false, options.autolock, options.autolockNodes),
    autoungrabify: defVal(false, options.autoungrabify, options.autoungrabifyNodes),
    autounselectify: defVal(false, options.autounselectify),
    styleEnabled: options.styleEnabled === undefined ? head : options.styleEnabled,
    zoom: number$1(options.zoom) ? options.zoom : 1,
    pan: {
      x: plainObject(options.pan) && number$1(options.pan.x) ? options.pan.x : 0,
      y: plainObject(options.pan) && number$1(options.pan.y) ? options.pan.y : 0
    },
    animation: {
      // object for currently-running animations
      current: [],
      queue: []
    },
    hasCompoundNodes: false,
    multiClickDebounceTime: defVal(250, options.multiClickDebounceTime)
  };
  this.createEmitter();

  // set selection type
  this.selectionType(options.selectionType);

  // init zoom bounds
  this.zoomRange({
    min: options.minZoom,
    max: options.maxZoom
  });
  var loadExtData = function loadExtData(extData, next) {
    var anyIsPromise = extData.some(promise);
    if (anyIsPromise) {
      return Promise$1.all(extData).then(next); // load all data asynchronously, then exec rest of init
    } else {
      next(extData); // exec synchronously for convenience
    }
  };

  // start with the default stylesheet so we have something before loading an external stylesheet
  if (_p.styleEnabled) {
    cy.setStyle([]);
  }

  // create the renderer
  var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options
  cy.initRenderer(rendererOptions);
  var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {
    cy.notifications(false);

    // remove old elements
    var oldEles = cy.mutableElements();
    if (oldEles.length > 0) {
      oldEles.remove();
    }
    if (elements != null) {
      if (plainObject(elements) || array(elements)) {
        cy.add(elements);
      }
    }
    cy.one('layoutready', function (e) {
      cy.notifications(true);
      cy.emit(e); // we missed this event by turning notifications off, so pass it on

      cy.one('load', onload);
      cy.emitAndNotify('load');
    }).one('layoutstop', function () {
      cy.one('done', ondone);
      cy.emit('done');
    });
    var layoutOpts = extend({}, cy._private.options.layout);
    layoutOpts.eles = cy.elements();
    cy.layout(layoutOpts).run();
  };
  loadExtData([options.style, options.elements], function (thens) {
    var initStyle = thens[0];
    var initEles = thens[1];

    // init style
    if (_p.styleEnabled) {
      cy.style().append(initStyle);
    }

    // initial load
    setElesAndLayout(initEles, function () {
      // onready
      cy.startAnimationLoop();
      _p.ready = true;

      // if a ready callback is specified as an option, the bind it
      if (fn$6(options.ready)) {
        cy.on('ready', options.ready);
      }

      // bind all the ready handlers registered before creating this instance
      for (var i = 0; i < readies.length; i++) {
        var fn = readies[i];
        cy.on('ready', fn);
      }
      if (reg) {
        reg.readies = [];
      } // clear b/c we've bound them all and don't want to keep it around in case a new core uses the same div etc

      cy.emit('ready');
    }, options.done);
  });
};
var corefn = Core.prototype; // short alias

extend(corefn, {
  instanceString: function instanceString() {
    return 'core';
  },
  isReady: function isReady() {
    return this._private.ready;
  },
  destroyed: function destroyed() {
    return this._private.destroyed;
  },
  ready: function ready(fn) {
    if (this.isReady()) {
      this.emitter().emit('ready', [], fn); // just calls fn as though triggered via ready event
    } else {
      this.on('ready', fn);
    }
    return this;
  },
  destroy: function destroy() {
    var cy = this;
    if (cy.destroyed()) return;
    cy.stopAnimationLoop();
    cy.destroyRenderer();
    this.emit('destroy');
    cy._private.destroyed = true;
    return cy;
  },
  hasElementWithId: function hasElementWithId(id) {
    return this._private.elements.hasElementWithId(id);
  },
  getElementById: function getElementById(id) {
    return this._private.elements.getElementById(id);
  },
  hasCompoundNodes: function hasCompoundNodes() {
    return this._private.hasCompoundNodes;
  },
  headless: function headless() {
    return this._private.renderer.isHeadless();
  },
  styleEnabled: function styleEnabled() {
    return this._private.styleEnabled;
  },
  addToPool: function addToPool(eles) {
    this._private.elements.merge(eles);
    return this; // chaining
  },
  removeFromPool: function removeFromPool(eles) {
    this._private.elements.unmerge(eles);
    return this;
  },
  container: function container() {
    return this._private.container || null;
  },
  window: function window() {
    var container = this._private.container;
    if (container == null) return _window;
    var ownerDocument = this._private.container.ownerDocument;
    if (ownerDocument === undefined || ownerDocument == null) {
      return _window;
    }
    return ownerDocument.defaultView || _window;
  },
  mount: function mount(container) {
    if (container == null) {
      return;
    }
    var cy = this;
    var _p = cy._private;
    var options = _p.options;
    if (!htmlElement(container) && htmlElement(container[0])) {
      container = container[0];
    }
    cy.stopAnimationLoop();
    cy.destroyRenderer();
    _p.container = container;
    _p.styleEnabled = true;
    cy.invalidateSize();
    cy.initRenderer(extend({}, options, options.renderer, {
      // allow custom renderer name to be re-used, otherwise use canvas
      name: options.renderer.name === 'null' ? 'canvas' : options.renderer.name
    }));
    cy.startAnimationLoop();
    cy.style(options.style);
    cy.emit('mount');
    return cy;
  },
  unmount: function unmount() {
    var cy = this;
    cy.stopAnimationLoop();
    cy.destroyRenderer();
    cy.initRenderer({
      name: 'null'
    });
    cy.emit('unmount');
    return cy;
  },
  options: function options() {
    return copy(this._private.options);
  },
  json: function json(obj) {
    var cy = this;
    var _p = cy._private;
    var eles = cy.mutableElements();
    var getFreshRef = function getFreshRef(ele) {
      return cy.getElementById(ele.id());
    };
    if (plainObject(obj)) {
      // set

      cy.startBatch();
      if (obj.elements) {
        var idInJson = {};
        var updateEles = function updateEles(jsons, gr) {
          var toAdd = [];
          var toMod = [];
          for (var i = 0; i < jsons.length; i++) {
            var json = jsons[i];
            if (!json.data.id) {
              warn('cy.json() cannot handle elements without an ID attribute');
              continue;
            }
            var id = '' + json.data.id; // id must be string
            var ele = cy.getElementById(id);
            idInJson[id] = true;
            if (ele.length !== 0) {
              // existing element should be updated
              toMod.push({
                ele: ele,
                json: json
              });
            } else {
              // otherwise should be added
              if (gr) {
                json.group = gr;
                toAdd.push(json);
              } else {
                toAdd.push(json);
              }
            }
          }
          cy.add(toAdd);
          for (var _i = 0; _i < toMod.length; _i++) {
            var _toMod$_i = toMod[_i],
              _ele = _toMod$_i.ele,
              _json = _toMod$_i.json;
            _ele.json(_json);
          }
        };
        if (array(obj.elements)) {
          // elements: []
          updateEles(obj.elements);
        } else {
          // elements: { nodes: [], edges: [] }
          var grs = ['nodes', 'edges'];
          for (var i = 0; i < grs.length; i++) {
            var gr = grs[i];
            var elements = obj.elements[gr];
            if (array(elements)) {
              updateEles(elements, gr);
            }
          }
        }
        var parentsToRemove = cy.collection();
        eles.filter(function (ele) {
          return !idInJson[ele.id()];
        }).forEach(function (ele) {
          if (ele.isParent()) {
            parentsToRemove.merge(ele);
          } else {
            ele.remove();
          }
        });

        // so that children are not removed w/parent
        parentsToRemove.forEach(function (ele) {
          return ele.children().move({
            parent: null
          });
        });

        // intermediate parents may be moved by prior line, so make sure we remove by fresh refs
        parentsToRemove.forEach(function (ele) {
          return getFreshRef(ele).remove();
        });
      }
      if (obj.style) {
        cy.style(obj.style);
      }
      if (obj.zoom != null && obj.zoom !== _p.zoom) {
        cy.zoom(obj.zoom);
      }
      if (obj.pan) {
        if (obj.pan.x !== _p.pan.x || obj.pan.y !== _p.pan.y) {
          cy.pan(obj.pan);
        }
      }
      if (obj.data) {
        cy.data(obj.data);
      }
      var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];
      for (var _i2 = 0; _i2 < fields.length; _i2++) {
        var f = fields[_i2];
        if (obj[f] != null) {
          cy[f](obj[f]);
        }
      }
      cy.endBatch();
      return this; // chaining
    } else {
      // get
      var flat = !!obj;
      var json = {};
      if (flat) {
        json.elements = this.elements().map(function (ele) {
          return ele.json();
        });
      } else {
        json.elements = {};
        eles.forEach(function (ele) {
          var group = ele.group();
          if (!json.elements[group]) {
            json.elements[group] = [];
          }
          json.elements[group].push(ele.json());
        });
      }
      if (this._private.styleEnabled) {
        json.style = cy.style().json();
      }
      json.data = copy(cy.data());
      var options = _p.options;
      json.zoomingEnabled = _p.zoomingEnabled;
      json.userZoomingEnabled = _p.userZoomingEnabled;
      json.zoom = _p.zoom;
      json.minZoom = _p.minZoom;
      json.maxZoom = _p.maxZoom;
      json.panningEnabled = _p.panningEnabled;
      json.userPanningEnabled = _p.userPanningEnabled;
      json.pan = copy(_p.pan);
      json.boxSelectionEnabled = _p.boxSelectionEnabled;
      json.renderer = copy(options.renderer);
      json.hideEdgesOnViewport = options.hideEdgesOnViewport;
      json.textureOnViewport = options.textureOnViewport;
      json.wheelSensitivity = options.wheelSensitivity;
      json.motionBlur = options.motionBlur;
      json.multiClickDebounceTime = options.multiClickDebounceTime;
      return json;
    }
  }
});
corefn.$id = corefn.getElementById;
[corefn$9, corefn$8, elesfn, corefn$7, corefn$6, corefn$5, corefn$4, corefn$3, corefn$2, corefn$1, fn].forEach(function (props) {
  extend(corefn, props);
});

/* eslint-disable no-unused-vars */
var defaults$7 = {
  fit: true,
  // whether to fit the viewport to the graph
  directed: false,
  // whether the tree is directed downwards (or edges can point in any direction if false)
  direction: 'downward',
  // determines the direction in which the tree structure is drawn.  The possible values are 'downward', 'upward', 'rightward', or 'leftward'.
  padding: 30,
  // padding on fit
  circle: false,
  // put depths in concentric circles if true, put depths top down if false
  grid: false,
  // whether to create an even grid into which the DAG is placed (circle:false only)
  spacingFactor: 1.75,
  // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)
  boundingBox: undefined,
  // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  avoidOverlap: true,
  // prevents node overlap, may overflow boundingBox if not enough space
  nodeDimensionsIncludeLabels: false,
  // Excludes the label when calculating node bounding boxes for the layout algorithm
  roots: undefined,
  // the roots of the trees
  depthSort: undefined,
  // a sorting function to order nodes at equal depth. e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  animate: false,
  // whether to transition the node positions
  animationDuration: 500,
  // duration of animation in ms if enabled
  animationEasing: undefined,
  // easing of animation if enabled,
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts
  ready: undefined,
  // callback on layoutready
  stop: undefined,
  // callback on layoutstop
  transform: function transform(node, position) {
    return position;
  } // transform a given node position. Useful for changing flow direction in discrete layouts
};
var deprecatedOptionDefaults = {
  maximal: false,
  // whether to shift nodes down their natural BFS depths in order to avoid upwards edges (DAGS only); setting acyclic to true sets maximal to true also
  acyclic: false // whether the tree is acyclic and thus a node could be shifted (due to the maximal option) multiple times without causing an infinite loop; setting to true sets maximal to true also; if you are uncertain whether a tree is acyclic, set to false to avoid potential infinite loops
};

/* eslint-enable */

var getInfo = function getInfo(ele) {
  return ele.scratch('breadthfirst');
};
var setInfo = function setInfo(ele, obj) {
  return ele.scratch('breadthfirst', obj);
};
function BreadthFirstLayout(options) {
  this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);
}
BreadthFirstLayout.prototype.run = function () {
  var options = this.options;
  var cy = options.cy;
  var eles = options.eles;
  var nodes = eles.nodes().filter(function (n) {
    return n.isChildless();
  });
  var graph = eles;
  var directed = options.directed;
  var maximal = options.acyclic || options.maximal || options.maximalAdjustments > 0; // maximalAdjustments for compat. w/ old code; also, setting acyclic to true sets maximal to true

  var hasBoundingBox = !!options.boundingBox;
  var bb = makeBoundingBox(hasBoundingBox ? options.boundingBox : structuredClone(cy.extent()));
  var roots;
  if (elementOrCollection(options.roots)) {
    roots = options.roots;
  } else if (array(options.roots)) {
    var rootsArray = [];
    for (var i = 0; i < options.roots.length; i++) {
      var id = options.roots[i];
      var ele = cy.getElementById(id);
      rootsArray.push(ele);
    }
    roots = cy.collection(rootsArray);
  } else if (string(options.roots)) {
    roots = cy.$(options.roots);
  } else {
    if (directed) {
      roots = nodes.roots();
    } else {
      var components = eles.components();
      roots = cy.collection();
      var _loop = function _loop() {
        var comp = components[_i];
        var maxDegree = comp.maxDegree(false);
        var compRoots = comp.filter(function (ele) {
          return ele.degree(false) === maxDegree;
        });
        roots = roots.add(compRoots);
      };
      for (var _i = 0; _i < components.length; _i++) {
        _loop();
      }
    }
  }
  var depths = [];
  var foundByBfs = {};
  var addToDepth = function addToDepth(ele, d) {
    if (depths[d] == null) {
      depths[d] = [];
    }
    var i = depths[d].length;
    depths[d].push(ele);
    setInfo(ele, {
      index: i,
      depth: d
    });
  };
  var changeDepth = function changeDepth(ele, newDepth) {
    var _getInfo = getInfo(ele),
      depth = _getInfo.depth,
      index = _getInfo.index;
    depths[depth][index] = null;

    // add only childless nodes
    if (ele.isChildless()) addToDepth(ele, newDepth);
  };

  // find the depths of the nodes
  graph.bfs({
    roots: roots,
    directed: options.directed,
    visit: function visit(node, edge, pNode, i, depth) {
      var ele = node[0];
      var id = ele.id();

      // add only childless nodes
      if (ele.isChildless()) addToDepth(ele, depth);
      foundByBfs[id] = true;
    }
  });

  // check for nodes not found by bfs
  var orphanNodes = [];
  for (var _i2 = 0; _i2 < nodes.length; _i2++) {
    var _ele = nodes[_i2];
    if (foundByBfs[_ele.id()]) {
      continue;
    } else {
      orphanNodes.push(_ele);
    }
  }

  // assign the nodes a depth and index
  var assignDepthsAt = function assignDepthsAt(i) {
    var eles = depths[i];
    for (var j = 0; j < eles.length; j++) {
      var _ele2 = eles[j];
      if (_ele2 == null) {
        eles.splice(j, 1);
        j--;
        continue;
      }
      setInfo(_ele2, {
        depth: i,
        index: j
      });
    }
  };
  var adjustMaximally = function adjustMaximally(ele, shifted) {
    var eInfo = getInfo(ele);
    var incomers = ele.incomers().filter(function (el) {
      return el.isNode() && eles.has(el);
    });
    var maxDepth = -1;
    var id = ele.id();
    for (var k = 0; k < incomers.length; k++) {
      var incmr = incomers[k];
      var iInfo = getInfo(incmr);
      maxDepth = Math.max(maxDepth, iInfo.depth);
    }
    if (eInfo.depth <= maxDepth) {
      if (!options.acyclic && shifted[id]) {
        return null;
      }
      var newDepth = maxDepth + 1;
      changeDepth(ele, newDepth);
      shifted[id] = newDepth;
      return true;
    }
    return false;
  };

  // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)
  if (directed && maximal) {
    var Q = [];
    var shifted = {};
    var enqueue = function enqueue(n) {
      return Q.push(n);
    };
    var dequeue = function dequeue() {
      return Q.shift();
    };
    nodes.forEach(function (n) {
      return Q.push(n);
    });
    while (Q.length > 0) {
      var _ele3 = dequeue();
      var didShift = adjustMaximally(_ele3, shifted);
      if (didShift) {
        _ele3.outgoers().filter(function (el) {
          return el.isNode() && eles.has(el);
        }).forEach(enqueue);
      } else if (didShift === null) {
        warn('Detected double maximal shift for node `' + _ele3.id() + '`.  Bailing maximal adjustment due to cycle.  Use `options.maximal: true` only on DAGs.');
        break; // exit on failure
      }
    }
  }

  // find min distance we need to leave between nodes
  var minDistance = 0;
  if (options.avoidOverlap) {
    for (var _i3 = 0; _i3 < nodes.length; _i3++) {
      var n = nodes[_i3];
      var nbb = n.layoutDimensions(options);
      var w = nbb.w;
      var h = nbb.h;
      minDistance = Math.max(minDistance, w, h);
    }
  }

  // get the weighted percent for an element based on its connectivity to other levels
  var cachedWeightedPercent = {};
  var getWeightedPercent = function getWeightedPercent(ele) {
    if (cachedWeightedPercent[ele.id()]) {
      return cachedWeightedPercent[ele.id()];
    }
    var eleDepth = getInfo(ele).depth;
    var neighbors = ele.neighborhood();
    var percent = 0;
    var samples = 0;
    for (var _i4 = 0; _i4 < neighbors.length; _i4++) {
      var neighbor = neighbors[_i4];
      if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {
        continue;
      }
      var bf = getInfo(neighbor);
      if (bf == null) {
        continue;
      }
      var index = bf.index;
      var depth = bf.depth;

      // unassigned neighbours shouldn't affect the ordering
      if (index == null || depth == null) {
        continue;
      }
      var nDepth = depths[depth].length;
      if (depth < eleDepth) {
        // only get influenced by elements above
        percent += index / nDepth;
        samples++;
      }
    }
    samples = Math.max(1, samples);
    percent = percent / samples;
    if (samples === 0) {
      // put lone nodes at the start
      percent = 0;
    }
    cachedWeightedPercent[ele.id()] = percent;
    return percent;
  };

  // rearrange the indices in each depth level based on connectivity
  var sortFn = function sortFn(a, b) {
    var apct = getWeightedPercent(a);
    var bpct = getWeightedPercent(b);
    var diff = apct - bpct;
    if (diff === 0) {
      return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons
    } else {
      return diff;
    }
  };
  if (options.depthSort !== undefined) {
    sortFn = options.depthSort;
  }
  var depthsLen = depths.length;

  // sort each level to make connected nodes closer
  for (var _i5 = 0; _i5 < depthsLen; _i5++) {
    depths[_i5].sort(sortFn);
    assignDepthsAt(_i5);
  }

  // assign orphan nodes to a new top-level depth
  var orphanDepth = [];
  for (var _i6 = 0; _i6 < orphanNodes.length; _i6++) {
    orphanDepth.push(orphanNodes[_i6]);
  }
  var assignDepths = function assignDepths() {
    for (var _i7 = 0; _i7 < depthsLen; _i7++) {
      assignDepthsAt(_i7);
    }
  };

  // add a new top-level depth only when there are orphan nodes
  if (orphanDepth.length) {
    depths.unshift(orphanDepth);
    depthsLen = depths.length;
    assignDepths();
  }
  var biggestDepthSize = 0;
  for (var _i8 = 0; _i8 < depthsLen; _i8++) {
    biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);
  }
  var center = {
    x: bb.x1 + bb.w / 2,
    y: bb.y1 + bb.h / 2
  };

  // average node size
  var aveNodeSize = nodes.reduce(function (acc, node) {
    return function (box) {
      return {
        w: acc.w === -1 ? box.w : (acc.w + box.w) / 2,
        h: acc.h === -1 ? box.h : (acc.h + box.h) / 2
      };
    }(node.boundingBox({
      includeLabels: options.nodeDimensionsIncludeLabels
    }));
  }, {
    w: -1,
    h: -1
  });
  var distanceY = Math.max(
  // only one depth
  depthsLen === 1 ? 0 :
  // inside a bounding box, no need for top & bottom padding
  hasBoundingBox ? (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen - 1) : (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen + 1), minDistance);
  var maxDepthSize = depths.reduce(function (max, eles) {
    return Math.max(max, eles.length);
  }, 0);
  var getPositionTopBottom = function getPositionTopBottom(ele) {
    var _getInfo2 = getInfo(ele),
      depth = _getInfo2.depth,
      index = _getInfo2.index;
    if (options.circle) {
      var radiusStepSize = Math.min(bb.w / 2 / depthsLen, bb.h / 2 / depthsLen);
      radiusStepSize = Math.max(radiusStepSize, minDistance);
      var radius = radiusStepSize * depth + radiusStepSize - (depthsLen > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);
      var theta = 2 * Math.PI / depths[depth].length * index;
      if (depth === 0 && depths[0].length === 1) {
        radius = 1;
      }
      return {
        x: center.x + radius * Math.cos(theta),
        y: center.y + radius * Math.sin(theta)
      };
    } else {
      var depthSize = depths[depth].length;
      var distanceX = Math.max(
      // only one depth
      depthSize === 1 ? 0 :
      // inside a bounding box, no need for left & right padding
      hasBoundingBox ? (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) - 1) : (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) + 1), minDistance);
      var epos = {
        x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,
        y: center.y + (depth + 1 - (depthsLen + 1) / 2) * distanceY
      };
      return epos;
    }
  };
  var rotateDegrees = {
    'downward': 0,
    'leftward': 90,
    'upward': 180,
    'rightward': -90
  };
  if (Object.keys(rotateDegrees).indexOf(options.direction) === -1) {
    error("Invalid direction '".concat(options.direction, "' specified for breadthfirst layout. Valid values are: ").concat(Object.keys(rotateDegrees).join(', ')));
  }
  var getPosition = function getPosition(ele) {
    return rotatePosAndSkewByBox(getPositionTopBottom(ele), bb, rotateDegrees[options.direction]);
  };
  eles.nodes().layoutPositions(this, options, getPosition);
  return this; // chaining
};

var defaults$6 = {
  fit: true,
  // whether to fit the viewport to the graph
  padding: 30,
  // the padding on fit
  boundingBox: undefined,
  // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  avoidOverlap: true,
  // prevents node overlap, may overflow boundingBox and radius if not enough space
  nodeDimensionsIncludeLabels: false,
  // Excludes the label when calculating node bounding boxes for the layout algorithm
  spacingFactor: undefined,
  // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  radius: undefined,
  // the radius of the circle
  startAngle: 3 / 2 * Math.PI,
  // where nodes start in radians
  sweep: undefined,
  // how many radians should be between the first and last node (defaults to full circle)
  clockwise: true,
  // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  sort: undefined,
  // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  animate: false,
  // whether to transition the node positions
  animationDuration: 500,
  // duration of animation in ms if enabled
  animationEasing: undefined,
  // easing of animation if enabled
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts
  ready: undefined,
  // callback on layoutready
  stop: undefined,
  // callback on layoutstop
  transform: function transform(node, position) {
    return position;
  } // transform a given node position. Useful for changing flow direction in discrete layouts 
};
function CircleLayout(options) {
  this.options = extend({}, defaults$6, options);
}
CircleLayout.prototype.run = function () {
  var params = this.options;
  var options = params;
  var cy = params.cy;
  var eles = options.eles;
  var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  var nodes = eles.nodes().not(':parent');
  if (options.sort) {
    nodes = nodes.sort(options.sort);
  }
  var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
    x1: 0,
    y1: 0,
    w: cy.width(),
    h: cy.height()
  });
  var center = {
    x: bb.x1 + bb.w / 2,
    y: bb.y1 + bb.h / 2
  };
  var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / nodes.length : options.sweep;
  var dTheta = sweep / Math.max(1, nodes.length - 1);
  var r;
  var minDistance = 0;
  for (var i = 0; i < nodes.length; i++) {
    var n = nodes[i];
    var nbb = n.layoutDimensions(options);
    var w = nbb.w;
    var h = nbb.h;
    minDistance = Math.max(minDistance, w, h);
  }
  if (number$1(options.radius)) {
    r = options.radius;
  } else if (nodes.length <= 1) {
    r = 0;
  } else {
    r = Math.min(bb.h, bb.w) / 2 - minDistance;
  }

  // calculate the radius
  if (nodes.length > 1 && options.avoidOverlap) {
    // but only if more than one node (can't overlap)
    minDistance *= 1.75; // just to have some nice spacing

    var dcos = Math.cos(dTheta) - Math.cos(0);
    var dsin = Math.sin(dTheta) - Math.sin(0);
    var rMin = Math.sqrt(minDistance * minDistance / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
    r = Math.max(rMin, r);
  }
  var getPos = function getPos(ele, i) {
    var theta = options.startAngle + i * dTheta * (clockwise ? 1 : -1);
    var rx = r * Math.cos(theta);
    var ry = r * Math.sin(theta);
    var pos = {
      x: center.x + rx,
      y: center.y + ry
    };
    return pos;
  };
  eles.nodes().layoutPositions(this, options, getPos);
  return this; // chaining
};

var defaults$5 = {
  fit: true,
  // whether to fit the viewport to the graph
  padding: 30,
  // the padding on fit
  startAngle: 3 / 2 * Math.PI,
  // where nodes start in radians
  sweep: undefined,
  // how many radians should be between the first and last node (defaults to full circle)
  clockwise: true,
  // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  equidistant: false,
  // whether levels have an equal radial distance betwen them, may cause bounding box overflow
  minNodeSpacing: 10,
  // min spacing between outside of nodes (used for radius adjustment)
  boundingBox: undefined,
  // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  avoidOverlap: true,
  // prevents node overlap, may overflow boundingBox if not enough space
  nodeDimensionsIncludeLabels: false,
  // Excludes the label when calculating node bounding boxes for the layout algorithm
  height: undefined,
  // height of layout area (overrides container height)
  width: undefined,
  // width of layout area (overrides container width)
  spacingFactor: undefined,
  // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  concentric: function concentric(node) {
    // returns numeric value for each node, placing higher nodes in levels towards the centre
    return node.degree();
  },
  levelWidth: function levelWidth(nodes) {
    // the variation of concentric values in each level
    return nodes.maxDegree() / 4;
  },
  animate: false,
  // whether to transition the node positions
  animationDuration: 500,
  // duration of animation in ms if enabled
  animationEasing: undefined,
  // easing of animation if enabled
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts
  ready: undefined,
  // callback on layoutready
  stop: undefined,
  // callback on layoutstop
  transform: function transform(node, position) {
    return position;
  } // transform a given node position. Useful for changing flow direction in discrete layouts
};
function ConcentricLayout(options) {
  this.options = extend({}, defaults$5, options);
}
ConcentricLayout.prototype.run = function () {
  var params = this.options;
  var options = params;
  var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  var cy = params.cy;
  var eles = options.eles;
  var nodes = eles.nodes().not(':parent');
  var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
    x1: 0,
    y1: 0,
    w: cy.width(),
    h: cy.height()
  });
  var center = {
    x: bb.x1 + bb.w / 2,
    y: bb.y1 + bb.h / 2
  };
  var nodeValues = []; // { node, value }
  var maxNodeSize = 0;
  for (var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    var value = undefined;

    // calculate the node value
    value = options.concentric(node);
    nodeValues.push({
      value: value,
      node: node
    });

    // for style mapping
    node._private.scratch.concentric = value;
  }

  // in case we used the `concentric` in style
  nodes.updateStyle();

  // calculate max size now based on potentially updated mappers
  for (var _i = 0; _i < nodes.length; _i++) {
    var _node = nodes[_i];
    var nbb = _node.layoutDimensions(options);
    maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);
  }

  // sort node values in descreasing order
  nodeValues.sort(function (a, b) {
    return b.value - a.value;
  });
  var levelWidth = options.levelWidth(nodes);

  // put the values into levels
  var levels = [[]];
  var currentLevel = levels[0];
  for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {
    var val = nodeValues[_i2];
    if (currentLevel.length > 0) {
      var diff = Math.abs(currentLevel[0].value - val.value);
      if (diff >= levelWidth) {
        currentLevel = [];
        levels.push(currentLevel);
      }
    }
    currentLevel.push(val);
  }

  // create positions from levels

  var minDist = maxNodeSize + options.minNodeSpacing; // min dist between nodes

  if (!options.avoidOverlap) {
    // then strictly constrain to bb
    var firstLvlHasMulti = levels.length > 0 && levels[0].length > 1;
    var maxR = Math.min(bb.w, bb.h) / 2 - minDist;
    var rStep = maxR / (levels.length + firstLvlHasMulti ? 1 : 0);
    minDist = Math.min(minDist, rStep);
  }

  // find the metrics for each level
  var r = 0;
  for (var _i3 = 0; _i3 < levels.length; _i3++) {
    var level = levels[_i3];
    var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / level.length : options.sweep;
    var dTheta = level.dTheta = sweep / Math.max(1, level.length - 1);

    // calculate the radius
    if (level.length > 1 && options.avoidOverlap) {
      // but only if more than one node (can't overlap)
      var dcos = Math.cos(dTheta) - Math.cos(0);
      var dsin = Math.sin(dTheta) - Math.sin(0);
      var rMin = Math.sqrt(minDist * minDist / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping

      r = Math.max(rMin, r);
    }
    level.r = r;
    r += minDist;
  }
  if (options.equidistant) {
    var rDeltaMax = 0;
    var _r = 0;
    for (var _i4 = 0; _i4 < levels.length; _i4++) {
      var _level = levels[_i4];
      var rDelta = _level.r - _r;
      rDeltaMax = Math.max(rDeltaMax, rDelta);
    }
    _r = 0;
    for (var _i5 = 0; _i5 < levels.length; _i5++) {
      var _level2 = levels[_i5];
      if (_i5 === 0) {
        _r = _level2.r;
      }
      _level2.r = _r;
      _r += rDeltaMax;
    }
  }

  // calculate the node positions
  var pos = {}; // id => position
  for (var _i6 = 0; _i6 < levels.length; _i6++) {
    var _level3 = levels[_i6];
    var _dTheta = _level3.dTheta;
    var _r2 = _level3.r;
    for (var j = 0; j < _level3.length; j++) {
      var _val = _level3[j];
      var theta = options.startAngle + (clockwise ? 1 : -1) * _dTheta * j;
      var p = {
        x: center.x + _r2 * Math.cos(theta),
        y: center.y + _r2 * Math.sin(theta)
      };
      pos[_val.node.id()] = p;
    }
  }

  // position the nodes
  eles.nodes().layoutPositions(this, options, function (ele) {
    var id = ele.id();
    return pos[id];
  });
  return this; // chaining
};

/*
The CoSE layout was written by Gerardo Huck.
https://www.linkedin.com/in/gerardohuck/

Based on the following article:
http://dl.acm.org/citation.cfm?id=1498047

Modifications tracked on Github.
*/

var DEBUG;

/**
 * @brief :  default layout options
 */
var defaults$4 = {
  // Called on `layoutready`
  ready: function ready() {},
  // Called on `layoutstop`
  stop: function stop() {},
  // Whether to animate while running the layout
  // true : Animate continuously as the layout is running
  // false : Just show the end result
  // 'end' : Animate with the end result, from the initial positions to the end positions
  animate: true,
  // Easing of the animation for animate:'end'
  animationEasing: undefined,
  // The duration of the animation for animate:'end'
  animationDuration: undefined,
  // A function that determines whether the node should be animated
  // All nodes animated by default on animate enabled
  // Non-animated nodes are positioned immediately when the layout starts
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // The layout animates only after this many milliseconds for animate:true
  // (prevents flashing on fast runs)
  animationThreshold: 250,
  // Number of iterations between consecutive screen positions update
  refresh: 20,
  // Whether to fit the network view after when done
  fit: true,
  // Padding on fit
  padding: 30,
  // Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  boundingBox: undefined,
  // Excludes the label when calculating node bounding boxes for the layout algorithm
  nodeDimensionsIncludeLabels: false,
  // Randomize the initial positions of the nodes (true) or use existing positions (false)
  randomize: false,
  // Extra spacing between components in non-compound graphs
  componentSpacing: 40,
  // Node repulsion (non overlapping) multiplier
  nodeRepulsion: function nodeRepulsion(node) {
    return 2048;
  },
  // Node repulsion (overlapping) multiplier
  nodeOverlap: 4,
  // Ideal edge (non nested) length
  idealEdgeLength: function idealEdgeLength(edge) {
    return 32;
  },
  // Divisor to compute edge forces
  edgeElasticity: function edgeElasticity(edge) {
    return 32;
  },
  // Nesting factor (multiplier) to compute ideal edge length for nested edges
  nestingFactor: 1.2,
  // Gravity force (constant)
  gravity: 1,
  // Maximum number of iterations to perform
  numIter: 1000,
  // Initial temperature (maximum node displacement)
  initialTemp: 1000,
  // Cooling factor (how the temperature is reduced between consecutive iterations
  coolingFactor: 0.99,
  // Lower temperature threshold (below this point the layout will end)
  minTemp: 1.0
};

/**
 * @brief       : constructor
 * @arg options : object containing layout options
 */
function CoseLayout(options) {
  this.options = extend({}, defaults$4, options);
  this.options.layout = this;

  // Exclude any edge that has a source or target node that is not in the set of passed-in nodes
  var nodes = this.options.eles.nodes();
  var edges = this.options.eles.edges();
  var notEdges = edges.filter(function (e) {
    var sourceId = e.source().data('id');
    var targetId = e.target().data('id');
    var hasSource = nodes.some(function (n) {
      return n.data('id') === sourceId;
    });
    var hasTarget = nodes.some(function (n) {
      return n.data('id') === targetId;
    });
    return !hasSource || !hasTarget;
  });
  this.options.eles = this.options.eles.not(notEdges);
}

/**
 * @brief : runs the layout
 */
CoseLayout.prototype.run = function () {
  var options = this.options;
  var cy = options.cy;
  var layout = this;
  layout.stopped = false;
  if (options.animate === true || options.animate === false) {
    layout.emit({
      type: 'layoutstart',
      layout: layout
    });
  }

  // Set DEBUG - Global variable
  if (true === options.debug) {
    DEBUG = true;
  } else {
    DEBUG = false;
  }

  // Initialize layout info
  var layoutInfo = createLayoutInfo(cy, layout, options);

  // Show LayoutInfo contents if debugging
  if (DEBUG) {
    printLayoutInfo(layoutInfo);
  }

  // If required, randomize node positions
  if (options.randomize) {
    randomizePositions(layoutInfo);
  }
  var startTime = performanceNow();
  var refresh = function refresh() {
    refreshPositions(layoutInfo, cy, options);

    // Fit the graph if necessary
    if (true === options.fit) {
      cy.fit(options.padding);
    }
  };
  var mainLoop = function mainLoop(i) {
    if (layout.stopped || i >= options.numIter) {
      // logDebug("Layout manually stopped. Stopping computation in step " + i);
      return false;
    }

    // Do one step in the phisical simulation
    step(layoutInfo, options);

    // Update temperature
    layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;
    // logDebug("New temperature: " + layoutInfo.temperature);

    if (layoutInfo.temperature < options.minTemp) {
      // logDebug("Temperature drop below minimum threshold. Stopping computation in step " + i);
      return false;
    }
    return true;
  };
  var done = function done() {
    if (options.animate === true || options.animate === false) {
      refresh();

      // Layout has finished
      layout.one('layoutstop', options.stop);
      layout.emit({
        type: 'layoutstop',
        layout: layout
      });
    } else {
      var nodes = options.eles.nodes();
      var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
      nodes.layoutPositions(layout, options, getScaledPos);
    }
  };
  var i = 0;
  var loopRet = true;
  if (options.animate === true) {
    var _frame = function frame() {
      var f = 0;
      while (loopRet && f < options.refresh) {
        loopRet = mainLoop(i);
        i++;
        f++;
      }
      if (!loopRet) {
        // it's done
        separateComponents(layoutInfo, options);
        done();
      } else {
        var now = performanceNow();
        if (now - startTime >= options.animationThreshold) {
          refresh();
        }
        requestAnimationFrame(_frame);
      }
    };
    _frame();
  } else {
    while (loopRet) {
      loopRet = mainLoop(i);
      i++;
    }
    separateComponents(layoutInfo, options);
    done();
  }
  return this; // chaining
};

/**
 * @brief : called on continuous layouts to stop them before they finish
 */
CoseLayout.prototype.stop = function () {
  this.stopped = true;
  if (this.thread) {
    this.thread.stop();
  }
  this.emit('layoutstop');
  return this; // chaining
};
CoseLayout.prototype.destroy = function () {
  if (this.thread) {
    this.thread.stop();
  }
  return this; // chaining
};

/**
 * @brief     : Creates an object which is contains all the data
 *              used in the layout process
 * @arg cy    : cytoscape.js object
 * @return    : layoutInfo object initialized
 */
var createLayoutInfo = function createLayoutInfo(cy, layout, options) {
  // Shortcut
  var edges = options.eles.edges();
  var nodes = options.eles.nodes();
  var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
    x1: 0,
    y1: 0,
    w: cy.width(),
    h: cy.height()
  });
  var layoutInfo = {
    isCompound: cy.hasCompoundNodes(),
    layoutNodes: [],
    idToIndex: {},
    nodeSize: nodes.size(),
    graphSet: [],
    indexToGraph: [],
    layoutEdges: [],
    edgeSize: edges.size(),
    temperature: options.initialTemp,
    clientWidth: bb.w,
    clientHeight: bb.h,
    boundingBox: bb
  };
  var components = options.eles.components();
  var id2cmptId = {};
  for (var i = 0; i < components.length; i++) {
    var component = components[i];
    for (var j = 0; j < component.length; j++) {
      var node = component[j];
      id2cmptId[node.id()] = i;
    }
  }

  // Iterate over all nodes, creating layout nodes
  for (var i = 0; i < layoutInfo.nodeSize; i++) {
    var n = nodes[i];
    var nbb = n.layoutDimensions(options);
    var tempNode = {};
    tempNode.isLocked = n.locked();
    tempNode.id = n.data('id');
    tempNode.parentId = n.data('parent');
    tempNode.cmptId = id2cmptId[n.id()];
    tempNode.children = [];
    tempNode.positionX = n.position('x');
    tempNode.positionY = n.position('y');
    tempNode.offsetX = 0;
    tempNode.offsetY = 0;
    tempNode.height = nbb.w;
    tempNode.width = nbb.h;
    tempNode.maxX = tempNode.positionX + tempNode.width / 2;
    tempNode.minX = tempNode.positionX - tempNode.width / 2;
    tempNode.maxY = tempNode.positionY + tempNode.height / 2;
    tempNode.minY = tempNode.positionY - tempNode.height / 2;
    tempNode.padLeft = parseFloat(n.style('padding'));
    tempNode.padRight = parseFloat(n.style('padding'));
    tempNode.padTop = parseFloat(n.style('padding'));
    tempNode.padBottom = parseFloat(n.style('padding'));

    // forces
    tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion;

    // Add new node
    layoutInfo.layoutNodes.push(tempNode);
    // Add entry to id-index map
    layoutInfo.idToIndex[tempNode.id] = i;
  }

  // Inline implementation of a queue, used for traversing the graph in BFS order
  var queue = [];
  var start = 0; // Points to the start the queue
  var end = -1; // Points to the end of the queue

  var tempGraph = [];

  // Second pass to add child information and
  // initialize queue for hierarchical traversal
  for (var i = 0; i < layoutInfo.nodeSize; i++) {
    var n = layoutInfo.layoutNodes[i];
    var p_id = n.parentId;
    // Check if node n has a parent node
    if (null != p_id) {
      // Add node Id to parent's list of children
      layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);
    } else {
      // If a node doesn't have a parent, then it's in the root graph
      queue[++end] = n.id;
      tempGraph.push(n.id);
    }
  }

  // Add root graph to graphSet
  layoutInfo.graphSet.push(tempGraph);

  // Traverse the graph, level by level,
  while (start <= end) {
    // Get the node to visit and remove it from queue
    var node_id = queue[start++];
    var node_ix = layoutInfo.idToIndex[node_id];
    var node = layoutInfo.layoutNodes[node_ix];
    var children = node.children;
    if (children.length > 0) {
      // Add children nodes as a new graph to graph set
      layoutInfo.graphSet.push(children);
      // Add children to que queue to be visited
      for (var i = 0; i < children.length; i++) {
        queue[++end] = children[i];
      }
    }
  }

  // Create indexToGraph map
  for (var i = 0; i < layoutInfo.graphSet.length; i++) {
    var graph = layoutInfo.graphSet[i];
    for (var j = 0; j < graph.length; j++) {
      var index = layoutInfo.idToIndex[graph[j]];
      layoutInfo.indexToGraph[index] = i;
    }
  }

  // Iterate over all edges, creating Layout Edges
  for (var i = 0; i < layoutInfo.edgeSize; i++) {
    var e = edges[i];
    var tempEdge = {};
    tempEdge.id = e.data('id');
    tempEdge.sourceId = e.data('source');
    tempEdge.targetId = e.data('target');

    // Compute ideal length
    var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;
    var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity;

    // Check if it's an inter graph edge
    var sourceIx = layoutInfo.idToIndex[tempEdge.sourceId];
    var targetIx = layoutInfo.idToIndex[tempEdge.targetId];
    var sourceGraph = layoutInfo.indexToGraph[sourceIx];
    var targetGraph = layoutInfo.indexToGraph[targetIx];
    if (sourceGraph != targetGraph) {
      // Find lowest common graph ancestor
      var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo);

      // Compute sum of node depths, relative to lca graph
      var lcaGraph = layoutInfo.graphSet[lca];
      var depth = 0;

      // Source depth
      var tempNode = layoutInfo.layoutNodes[sourceIx];
      while (-1 === lcaGraph.indexOf(tempNode.id)) {
        tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
        depth++;
      }

      // Target depth
      tempNode = layoutInfo.layoutNodes[targetIx];
      while (-1 === lcaGraph.indexOf(tempNode.id)) {
        tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
        depth++;
      }

      // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +
      //  ". Index: " + lca + " Contents: " + lcaGraph.toString() +
      //  ". Depth: " + depth);

      // Update idealLength
      idealLength *= depth * options.nestingFactor;
    }
    tempEdge.idealLength = idealLength;
    tempEdge.elasticity = elasticity;
    layoutInfo.layoutEdges.push(tempEdge);
  }

  // Finally, return layoutInfo object
  return layoutInfo;
};

/**
 * @brief : This function finds the index of the lowest common
 *          graph ancestor between 2 nodes in the subtree
 *          (from the graph hierarchy induced tree) whose
 *          root is graphIx
 *
 * @arg node1: node1's ID
 * @arg node2: node2's ID
 * @arg layoutInfo: layoutInfo object
 *
 */
var findLCA = function findLCA(node1, node2, layoutInfo) {
  // Find their common ancester, starting from the root graph
  var res = _findLCA_aux(node1, node2, 0, layoutInfo);
  if (2 > res.count) {
    // If aux function couldn't find the common ancester,
    // then it is the root graph
    return 0;
  } else {
    return res.graph;
  }
};

/**
 * @brief          : Auxiliary function used for LCA computation
 *
 * @arg node1      : node1's ID
 * @arg node2      : node2's ID
 * @arg graphIx    : subgraph index
 * @arg layoutInfo : layoutInfo object
 *
 * @return         : object of the form {count: X, graph: Y}, where:
 *                   X is the number of ancestors (max: 2) found in
 *                   graphIx (and it's subgraphs),
 *                   Y is the graph index of the lowest graph containing
 *                   all X nodes
 */
var _findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {
  var graph = layoutInfo.graphSet[graphIx];
  // If both nodes belongs to graphIx
  if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {
    return {
      count: 2,
      graph: graphIx
    };
  }

  // Make recursive calls for all subgraphs
  var c = 0;
  for (var i = 0; i < graph.length; i++) {
    var nodeId = graph[i];
    var nodeIx = layoutInfo.idToIndex[nodeId];
    var children = layoutInfo.layoutNodes[nodeIx].children;

    // If the node has no child, skip it
    if (0 === children.length) {
      continue;
    }
    var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];
    var result = _findLCA_aux(node1, node2, childGraphIx, layoutInfo);
    if (0 === result.count) {
      // Neither node1 nor node2 are present in this subgraph
      continue;
    } else if (1 === result.count) {
      // One of (node1, node2) is present in this subgraph
      c++;
      if (2 === c) {
        // We've already found both nodes, no need to keep searching
        break;
      }
    } else {
      // Both nodes are present in this subgraph
      return result;
    }
  }
  return {
    count: c,
    graph: graphIx
  };
};

/**
 * @brief: printsLayoutInfo into js console
 *         Only used for debbuging
 */
var printLayoutInfo; 

/**
 * @brief : Randomizes the position of all nodes
 */
var randomizePositions = function randomizePositions(layoutInfo, cy) {
  var width = layoutInfo.clientWidth;
  var height = layoutInfo.clientHeight;
  for (var i = 0; i < layoutInfo.nodeSize; i++) {
    var n = layoutInfo.layoutNodes[i];

    // No need to randomize compound nodes or locked nodes
    if (0 === n.children.length && !n.isLocked) {
      n.positionX = Math.random() * width;
      n.positionY = Math.random() * height;
    }
  }
};
var getScaleInBoundsFn = function getScaleInBoundsFn(layoutInfo, options, nodes) {
  var bb = layoutInfo.boundingBox;
  var coseBB = {
    x1: Infinity,
    x2: -Infinity,
    y1: Infinity,
    y2: -Infinity
  };
  if (options.boundingBox) {
    nodes.forEach(function (node) {
      var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[node.data('id')]];
      coseBB.x1 = Math.min(coseBB.x1, lnode.positionX);
      coseBB.x2 = Math.max(coseBB.x2, lnode.positionX);
      coseBB.y1 = Math.min(coseBB.y1, lnode.positionY);
      coseBB.y2 = Math.max(coseBB.y2, lnode.positionY);
    });
    coseBB.w = coseBB.x2 - coseBB.x1;
    coseBB.h = coseBB.y2 - coseBB.y1;
  }
  return function (ele, i) {
    var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];
    if (options.boundingBox) {
      // then add extra bounding box constraint
      // Handle single node case where coseBB.w or coseBB.h is 0
      var pctX = coseBB.w === 0 ? 0.5 : (lnode.positionX - coseBB.x1) / coseBB.w;
      var pctY = coseBB.h === 0 ? 0.5 : (lnode.positionY - coseBB.y1) / coseBB.h;
      return {
        x: bb.x1 + pctX * bb.w,
        y: bb.y1 + pctY * bb.h
      };
    } else {
      return {
        x: lnode.positionX,
        y: lnode.positionY
      };
    }
  };
};

/**
 * @brief          : Updates the positions of nodes in the network
 * @arg layoutInfo : LayoutInfo object
 * @arg cy         : Cytoscape object
 * @arg options    : Layout options
 */
var refreshPositions = function refreshPositions(layoutInfo, cy, options) {
  // var s = 'Refreshing positions';
  // logDebug(s);

  var layout = options.layout;
  var nodes = options.eles.nodes();
  var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  nodes.positions(getScaledPos);

  // Trigger layoutReady only on first call
  if (true !== layoutInfo.ready) {
    // s = 'Triggering layoutready';
    // logDebug(s);
    layoutInfo.ready = true;
    layout.one('layoutready', options.ready);
    layout.emit({
      type: 'layoutready',
      layout: this
    });
  }
};

/**
 * @brief : Logs a debug message in JS console, if DEBUG is ON
 */
// var logDebug = function(text) {
//   if (DEBUG) {
//     console.debug(text);
//   }
// };

/**
 * @brief          : Performs one iteration of the physical simulation
 * @arg layoutInfo : LayoutInfo object already initialized
 * @arg cy         : Cytoscape object
 * @arg options    : Layout options
 */
var step = function step(layoutInfo, options, _step) {
  // var s = "\n\n###############################";
  // s += "\nSTEP: " + step;
  // s += "\n###############################\n";
  // logDebug(s);

  // Calculate node repulsions
  calculateNodeForces(layoutInfo, options);
  // Calculate edge forces
  calculateEdgeForces(layoutInfo);
  // Calculate gravity forces
  calculateGravityForces(layoutInfo, options);
  // Propagate forces from parent to child
  propagateForces(layoutInfo);
  // Update positions based on calculated forces
  updatePositions(layoutInfo);
};

/**
 * @brief : Computes the node repulsion forces
 */
var calculateNodeForces = function calculateNodeForces(layoutInfo, options) {
  // Go through each of the graphs in graphSet
  // Nodes only repel each other if they belong to the same graph
  // var s = 'calculateNodeForces';
  // logDebug(s);
  for (var i = 0; i < layoutInfo.graphSet.length; i++) {
    var graph = layoutInfo.graphSet[i];
    var numNodes = graph.length;

    // s = "Set: " + graph.toString();
    // logDebug(s);

    // Now get all the pairs of nodes
    // Only get each pair once, (A, B) = (B, A)
    for (var j = 0; j < numNodes; j++) {
      var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
      for (var k = j + 1; k < numNodes; k++) {
        var node2 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[k]]];
        nodeRepulsion(node1, node2, layoutInfo, options);
      }
    }
  }
};
var randomDistance = function randomDistance(max) {
  return -1 + 2 * max * Math.random();
};

/**
 * @brief : Compute the node repulsion forces between a pair of nodes
 */
var nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {
  // var s = "Node repulsion. Node1: " + node1.id + " Node2: " + node2.id;

  var cmptId1 = node1.cmptId;
  var cmptId2 = node2.cmptId;
  if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {
    return;
  }

  // Get direction of line connecting both node centers
  var directionX = node2.positionX - node1.positionX;
  var directionY = node2.positionY - node1.positionY;
  var maxRandDist = 1;
  // s += "\ndirectionX: " + directionX + ", directionY: " + directionY;

  // If both centers are the same, apply a random force
  if (0 === directionX && 0 === directionY) {
    directionX = randomDistance(maxRandDist);
    directionY = randomDistance(maxRandDist);
  }
  var overlap = nodesOverlap(node1, node2, directionX, directionY);
  if (overlap > 0) {
    // s += "\nNodes DO overlap.";
    // s += "\nOverlap: " + overlap;
    // If nodes overlap, repulsion force is proportional
    // to the overlap
    var force = options.nodeOverlap * overlap;

    // Compute the module and components of the force vector
    var distance = Math.sqrt(directionX * directionX + directionY * directionY);
    // s += "\nDistance: " + distance;
    var forceX = force * directionX / distance;
    var forceY = force * directionY / distance;
  } else {
    // s += "\nNodes do NOT overlap.";
    // If there's no overlap, force is inversely proportional
    // to squared distance

    // Get clipping points for both nodes
    var point1 = findClippingPoint(node1, directionX, directionY);
    var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY);

    // Use clipping points to compute distance
    var distanceX = point2.x - point1.x;
    var distanceY = point2.y - point1.y;
    var distanceSqr = distanceX * distanceX + distanceY * distanceY;
    var distance = Math.sqrt(distanceSqr);
    // s += "\nDistance: " + distance;

    // Compute the module and components of the force vector
    var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;
    var forceX = force * distanceX / distance;
    var forceY = force * distanceY / distance;
  }

  // Apply force
  if (!node1.isLocked) {
    node1.offsetX -= forceX;
    node1.offsetY -= forceY;
  }
  if (!node2.isLocked) {
    node2.offsetX += forceX;
    node2.offsetY += forceY;
  }

  // s += "\nForceX: " + forceX + " ForceY: " + forceY;
  // logDebug(s);

  return;
};

/**
 * @brief  : Determines whether two nodes overlap or not
 * @return : Amount of overlapping (0 => no overlap)
 */
var nodesOverlap = function nodesOverlap(node1, node2, dX, dY) {
  if (dX > 0) {
    var overlapX = node1.maxX - node2.minX;
  } else {
    var overlapX = node2.maxX - node1.minX;
  }
  if (dY > 0) {
    var overlapY = node1.maxY - node2.minY;
  } else {
    var overlapY = node2.maxY - node1.minY;
  }
  if (overlapX >= 0 && overlapY >= 0) {
    return Math.sqrt(overlapX * overlapX + overlapY * overlapY);
  } else {
    return 0;
  }
};

/**
 * @brief : Finds the point in which an edge (direction dX, dY) intersects
 *          the rectangular bounding box of it's source/target node
 */
var findClippingPoint = function findClippingPoint(node, dX, dY) {
  // Shorcuts
  var X = node.positionX;
  var Y = node.positionY;
  var H = node.height || 1;
  var W = node.width || 1;
  var dirSlope = dY / dX;
  var nodeSlope = H / W;

  // var s = 'Computing clipping point of node ' + node.id +
  //   " . Height:  " + H + ", Width: " + W +
  //   "\nDirection " + dX + ", " + dY;
  //
  // Compute intersection
  var res = {};

  // Case: Vertical direction (up)
  if (0 === dX && 0 < dY) {
    res.x = X;
    // s += "\nUp direction";
    res.y = Y + H / 2;
    return res;
  }

  // Case: Vertical direction (down)
  if (0 === dX && 0 > dY) {
    res.x = X;
    res.y = Y + H / 2;
    // s += "\nDown direction";

    return res;
  }

  // Case: Intersects the right border
  if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
    res.x = X + W / 2;
    res.y = Y + W * dY / 2 / dX;
    // s += "\nRightborder";

    return res;
  }

  // Case: Intersects the left border
  if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
    res.x = X - W / 2;
    res.y = Y - W * dY / 2 / dX;
    // s += "\nLeftborder";

    return res;
  }

  // Case: Intersects the top border
  if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
    res.x = X + H * dX / 2 / dY;
    res.y = Y + H / 2;
    // s += "\nTop border";

    return res;
  }

  // Case: Intersects the bottom border
  if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
    res.x = X - H * dX / 2 / dY;
    res.y = Y - H / 2;
    // s += "\nBottom border";

    return res;
  }

  // s += "\nClipping point found at " + res.x + ", " + res.y;
  // logDebug(s);
  return res;
};

/**
 * @brief : Calculates all edge forces
 */
var calculateEdgeForces = function calculateEdgeForces(layoutInfo, options) {
  // Iterate over all edges
  for (var i = 0; i < layoutInfo.edgeSize; i++) {
    // Get edge, source & target nodes
    var edge = layoutInfo.layoutEdges[i];
    var sourceIx = layoutInfo.idToIndex[edge.sourceId];
    var source = layoutInfo.layoutNodes[sourceIx];
    var targetIx = layoutInfo.idToIndex[edge.targetId];
    var target = layoutInfo.layoutNodes[targetIx];

    // Get direction of line connecting both node centers
    var directionX = target.positionX - source.positionX;
    var directionY = target.positionY - source.positionY;

    // If both centers are the same, do nothing.
    // A random force has already been applied as node repulsion
    if (0 === directionX && 0 === directionY) {
      continue;
    }

    // Get clipping points for both nodes
    var point1 = findClippingPoint(source, directionX, directionY);
    var point2 = findClippingPoint(target, -1 * directionX, -1 * directionY);
    var lx = point2.x - point1.x;
    var ly = point2.y - point1.y;
    var l = Math.sqrt(lx * lx + ly * ly);
    var force = Math.pow(edge.idealLength - l, 2) / edge.elasticity;
    if (0 !== l) {
      var forceX = force * lx / l;
      var forceY = force * ly / l;
    } else {
      var forceX = 0;
      var forceY = 0;
    }

    // Add this force to target and source nodes
    if (!source.isLocked) {
      source.offsetX += forceX;
      source.offsetY += forceY;
    }
    if (!target.isLocked) {
      target.offsetX -= forceX;
      target.offsetY -= forceY;
    }

    // var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;
    // s += "\nDistance: " + l + " Force: (" + forceX + ", " + forceY + ")";
    // logDebug(s);
  }
};

/**
 * @brief : Computes gravity forces for all nodes
 */
var calculateGravityForces = function calculateGravityForces(layoutInfo, options) {
  if (options.gravity === 0) {
    return;
  }
  var distThreshold = 1;

  // var s = 'calculateGravityForces';
  // logDebug(s);
  for (var i = 0; i < layoutInfo.graphSet.length; i++) {
    var graph = layoutInfo.graphSet[i];
    var numNodes = graph.length;

    // s = "Set: " + graph.toString();
    // logDebug(s);

    // Compute graph center
    if (0 === i) {
      var centerX = layoutInfo.clientHeight / 2;
      var centerY = layoutInfo.clientWidth / 2;
    } else {
      // Get Parent node for this graph, and use its position as center
      var temp = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[0]]];
      var parent = layoutInfo.layoutNodes[layoutInfo.idToIndex[temp.parentId]];
      var centerX = parent.positionX;
      var centerY = parent.positionY;
    }
    // s = "Center found at: " + centerX + ", " + centerY;
    // logDebug(s);

    // Apply force to all nodes in graph
    for (var j = 0; j < numNodes; j++) {
      var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
      // s = "Node: " + node.id;

      if (node.isLocked) {
        continue;
      }
      var dx = centerX - node.positionX;
      var dy = centerY - node.positionY;
      var d = Math.sqrt(dx * dx + dy * dy);
      if (d > distThreshold) {
        var fx = options.gravity * dx / d;
        var fy = options.gravity * dy / d;
        node.offsetX += fx;
        node.offsetY += fy;
        // s += ": Applied force: " + fx + ", " + fy;
      }
      // logDebug(s);
    }
  }
};

/**
 * @brief          : This function propagates the existing offsets from
 *                   parent nodes to its descendents.
 * @arg layoutInfo : layoutInfo Object
 * @arg cy         : cytoscape Object
 * @arg options    : Layout options
 */
var propagateForces = function propagateForces(layoutInfo, options) {
  // Inline implementation of a queue, used for traversing the graph in BFS order
  var queue = [];
  var start = 0; // Points to the start the queue
  var end = -1; // Points to the end of the queue

  // logDebug('propagateForces');

  // Start by visiting the nodes in the root graph
  queue.push.apply(queue, layoutInfo.graphSet[0]);
  end += layoutInfo.graphSet[0].length;

  // Traverse the graph, level by level,
  while (start <= end) {
    // Get the node to visit and remove it from queue
    var nodeId = queue[start++];
    var nodeIndex = layoutInfo.idToIndex[nodeId];
    var node = layoutInfo.layoutNodes[nodeIndex];
    var children = node.children;

    // We only need to process the node if it's compound
    if (0 < children.length && !node.isLocked) {
      var offX = node.offsetX;
      var offY = node.offsetY;

      // var s = "Propagating offset from parent node : " + node.id +
      //   ". OffsetX: " + offX + ". OffsetY: " + offY;
      // s += "\n Children: " + children.toString();
      // logDebug(s);

      for (var i = 0; i < children.length; i++) {
        var childNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[children[i]]];
        // Propagate offset
        childNode.offsetX += offX;
        childNode.offsetY += offY;
        // Add children to queue to be visited
        queue[++end] = children[i];
      }

      // Reset parent offsets
      node.offsetX = 0;
      node.offsetY = 0;
    }
  }
};

/**
 * @brief : Updates the layout model positions, based on
 *          the accumulated forces
 */
var updatePositions = function updatePositions(layoutInfo, options) {
  // var s = 'Updating positions';
  // logDebug(s);

  // Reset boundaries for compound nodes
  for (var i = 0; i < layoutInfo.nodeSize; i++) {
    var n = layoutInfo.layoutNodes[i];
    if (0 < n.children.length) {
      // logDebug("Resetting boundaries of compound node: " + n.id);
      n.maxX = undefined;
      n.minX = undefined;
      n.maxY = undefined;
      n.minY = undefined;
    }
  }
  for (var i = 0; i < layoutInfo.nodeSize; i++) {
    var n = layoutInfo.layoutNodes[i];
    if (0 < n.children.length || n.isLocked) {
      // No need to set compound or locked node position
      // logDebug("Skipping position update of node: " + n.id);
      continue;
    }
    // s = "Node: " + n.id + " Previous position: (" +
    // n.positionX + ", " + n.positionY + ").";

    // Limit displacement in order to improve stability
    var tempForce = limitForce(n.offsetX, n.offsetY, layoutInfo.temperature);
    n.positionX += tempForce.x;
    n.positionY += tempForce.y;
    n.offsetX = 0;
    n.offsetY = 0;
    n.minX = n.positionX - n.width;
    n.maxX = n.positionX + n.width;
    n.minY = n.positionY - n.height;
    n.maxY = n.positionY + n.height;
    // s += " New Position: (" + n.positionX + ", " + n.positionY + ").";
    // logDebug(s);

    // Update ancestry boudaries
    _updateAncestryBoundaries(n, layoutInfo);
  }

  // Update size, position of compund nodes
  for (var i = 0; i < layoutInfo.nodeSize; i++) {
    var n = layoutInfo.layoutNodes[i];
    if (0 < n.children.length && !n.isLocked) {
      n.positionX = (n.maxX + n.minX) / 2;
      n.positionY = (n.maxY + n.minY) / 2;
      n.width = n.maxX - n.minX;
      n.height = n.maxY - n.minY;
      // s = "Updating position, size of compound node " + n.id;
      // s += "\nPositionX: " + n.positionX + ", PositionY: " + n.positionY;
      // s += "\nWidth: " + n.width + ", Height: " + n.height;
      // logDebug(s);
    }
  }
};

/**
 * @brief : Limits a force (forceX, forceY) to be not
 *          greater (in modulo) than max.
 8          Preserves force direction.
  */
var limitForce = function limitForce(forceX, forceY, max) {
  // var s = "Limiting force: (" + forceX + ", " + forceY + "). Max: " + max;
  var force = Math.sqrt(forceX * forceX + forceY * forceY);
  if (force > max) {
    var res = {
      x: max * forceX / force,
      y: max * forceY / force
    };
  } else {
    var res = {
      x: forceX,
      y: forceY
    };
  }

  // s += ".\nResult: (" + res.x + ", " + res.y + ")";
  // logDebug(s);

  return res;
};

/**
 * @brief : Function used for keeping track of compound node
 *          sizes, since they should bound all their subnodes.
 */
var _updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {
  // var s = "Propagating new position/size of node " + node.id;
  var parentId = node.parentId;
  if (null == parentId) {
    // If there's no parent, we are done
    // s += ". No parent node.";
    // logDebug(s);
    return;
  }

  // Get Parent Node
  var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];
  var flag = false;

  // MaxX
  if (null == p.maxX || node.maxX + p.padRight > p.maxX) {
    p.maxX = node.maxX + p.padRight;
    flag = true;
    // s += "\nNew maxX for parent node " + p.id + ": " + p.maxX;
  }

  // MinX
  if (null == p.minX || node.minX - p.padLeft < p.minX) {
    p.minX = node.minX - p.padLeft;
    flag = true;
    // s += "\nNew minX for parent node " + p.id + ": " + p.minX;
  }

  // MaxY
  if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {
    p.maxY = node.maxY + p.padBottom;
    flag = true;
    // s += "\nNew maxY for parent node " + p.id + ": " + p.maxY;
  }

  // MinY
  if (null == p.minY || node.minY - p.padTop < p.minY) {
    p.minY = node.minY - p.padTop;
    flag = true;
    // s += "\nNew minY for parent node " + p.id + ": " + p.minY;
  }

  // If updated boundaries, propagate changes upward
  if (flag) {
    // logDebug(s);
    return _updateAncestryBoundaries(p, layoutInfo);
  }

  // s += ". No changes in boundaries/position of parent node " + p.id;
  // logDebug(s);
  return;
};
var separateComponents = function separateComponents(layoutInfo, options) {
  var nodes = layoutInfo.layoutNodes;
  var components = [];
  for (var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    var cid = node.cmptId;
    var component = components[cid] = components[cid] || [];
    component.push(node);
  }
  var totalA = 0;
  for (var i = 0; i < components.length; i++) {
    var c = components[i];
    if (!c) {
      continue;
    }
    c.x1 = Infinity;
    c.x2 = -Infinity;
    c.y1 = Infinity;
    c.y2 = -Infinity;
    for (var j = 0; j < c.length; j++) {
      var n = c[j];
      c.x1 = Math.min(c.x1, n.positionX - n.width / 2);
      c.x2 = Math.max(c.x2, n.positionX + n.width / 2);
      c.y1 = Math.min(c.y1, n.positionY - n.height / 2);
      c.y2 = Math.max(c.y2, n.positionY + n.height / 2);
    }
    c.w = c.x2 - c.x1;
    c.h = c.y2 - c.y1;
    totalA += c.w * c.h;
  }
  components.sort(function (c1, c2) {
    return c2.w * c2.h - c1.w * c1.h;
  });
  var x = 0;
  var y = 0;
  var usedW = 0;
  var rowH = 0;
  var maxRowW = Math.sqrt(totalA) * layoutInfo.clientWidth / layoutInfo.clientHeight;
  for (var i = 0; i < components.length; i++) {
    var c = components[i];
    if (!c) {
      continue;
    }
    for (var j = 0; j < c.length; j++) {
      var n = c[j];
      if (!n.isLocked) {
        n.positionX += x - c.x1;
        n.positionY += y - c.y1;
      }
    }
    x += c.w + options.componentSpacing;
    usedW += c.w + options.componentSpacing;
    rowH = Math.max(rowH, c.h);
    if (usedW > maxRowW) {
      y += rowH + options.componentSpacing;
      x = 0;
      usedW = 0;
      rowH = 0;
    }
  }
};

var defaults$3 = {
  fit: true,
  // whether to fit the viewport to the graph
  padding: 30,
  // padding used on fit
  boundingBox: undefined,
  // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  avoidOverlap: true,
  // prevents node overlap, may overflow boundingBox if not enough space
  avoidOverlapPadding: 10,
  // extra spacing around nodes when avoidOverlap: true
  nodeDimensionsIncludeLabels: false,
  // Excludes the label when calculating node bounding boxes for the layout algorithm
  spacingFactor: undefined,
  // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  condense: false,
  // uses all available space on false, uses minimal space on true
  rows: undefined,
  // force num of rows in the grid
  cols: undefined,
  // force num of columns in the grid
  position: function position(node) {},
  // returns { row, col } for element
  sort: undefined,
  // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  animate: false,
  // whether to transition the node positions
  animationDuration: 500,
  // duration of animation in ms if enabled
  animationEasing: undefined,
  // easing of animation if enabled
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts
  ready: undefined,
  // callback on layoutready
  stop: undefined,
  // callback on layoutstop
  transform: function transform(node, position) {
    return position;
  } // transform a given node position. Useful for changing flow direction in discrete layouts 
};
function GridLayout(options) {
  this.options = extend({}, defaults$3, options);
}
GridLayout.prototype.run = function () {
  var params = this.options;
  var options = params;
  var cy = params.cy;
  var eles = options.eles;
  var nodes = eles.nodes().not(':parent');
  if (options.sort) {
    nodes = nodes.sort(options.sort);
  }
  var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
    x1: 0,
    y1: 0,
    w: cy.width(),
    h: cy.height()
  });
  if (bb.h === 0 || bb.w === 0) {
    eles.nodes().layoutPositions(this, options, function (ele) {
      return {
        x: bb.x1,
        y: bb.y1
      };
    });
  } else {
    // width/height * splits^2 = cells where splits is number of times to split width
    var cells = nodes.size();
    var splits = Math.sqrt(cells * bb.h / bb.w);
    var rows = Math.round(splits);
    var cols = Math.round(bb.w / bb.h * splits);
    var small = function small(val) {
      if (val == null) {
        return Math.min(rows, cols);
      } else {
        var min = Math.min(rows, cols);
        if (min == rows) {
          rows = val;
        } else {
          cols = val;
        }
      }
    };
    var large = function large(val) {
      if (val == null) {
        return Math.max(rows, cols);
      } else {
        var max = Math.max(rows, cols);
        if (max == rows) {
          rows = val;
        } else {
          cols = val;
        }
      }
    };
    var oRows = options.rows;
    var oCols = options.cols != null ? options.cols : options.columns;

    // if rows or columns were set in options, use those values
    if (oRows != null && oCols != null) {
      rows = oRows;
      cols = oCols;
    } else if (oRows != null && oCols == null) {
      rows = oRows;
      cols = Math.ceil(cells / rows);
    } else if (oRows == null && oCols != null) {
      cols = oCols;
      rows = Math.ceil(cells / cols);
    }

    // otherwise use the automatic values and adjust accordingly

    // if rounding was up, see if we can reduce rows or columns
    else if (cols * rows > cells) {
      var sm = small();
      var lg = large();

      // reducing the small side takes away the most cells, so try it first
      if ((sm - 1) * lg >= cells) {
        small(sm - 1);
      } else if ((lg - 1) * sm >= cells) {
        large(lg - 1);
      }
    } else {
      // if rounding was too low, add rows or columns
      while (cols * rows < cells) {
        var _sm = small();
        var _lg = large();

        // try to add to larger side first (adds less in multiplication)
        if ((_lg + 1) * _sm >= cells) {
          large(_lg + 1);
        } else {
          small(_sm + 1);
        }
      }
    }
    var cellWidth = bb.w / cols;
    var cellHeight = bb.h / rows;
    if (options.condense) {
      cellWidth = 0;
      cellHeight = 0;
    }
    if (options.avoidOverlap) {
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var pos = node._private.position;
        if (pos.x == null || pos.y == null) {
          // for bb
          pos.x = 0;
          pos.y = 0;
        }
        var nbb = node.layoutDimensions(options);
        var p = options.avoidOverlapPadding;
        var w = nbb.w + p;
        var h = nbb.h + p;
        cellWidth = Math.max(cellWidth, w);
        cellHeight = Math.max(cellHeight, h);
      }
    }
    var cellUsed = {}; // e.g. 'c-0-2' => true

    var used = function used(row, col) {
      return cellUsed['c-' + row + '-' + col] ? true : false;
    };
    var use = function use(row, col) {
      cellUsed['c-' + row + '-' + col] = true;
    };

    // to keep track of current cell position
    var row = 0;
    var col = 0;
    var moveToNextCell = function moveToNextCell() {
      col++;
      if (col >= cols) {
        col = 0;
        row++;
      }
    };

    // get a cache of all the manual positions
    var id2manPos = {};
    for (var _i = 0; _i < nodes.length; _i++) {
      var _node = nodes[_i];
      var rcPos = options.position(_node);
      if (rcPos && (rcPos.row !== undefined || rcPos.col !== undefined)) {
        // must have at least row or col def'd
        var _pos = {
          row: rcPos.row,
          col: rcPos.col
        };
        if (_pos.col === undefined) {
          // find unused col
          _pos.col = 0;
          while (used(_pos.row, _pos.col)) {
            _pos.col++;
          }
        } else if (_pos.row === undefined) {
          // find unused row
          _pos.row = 0;
          while (used(_pos.row, _pos.col)) {
            _pos.row++;
          }
        }
        id2manPos[_node.id()] = _pos;
        use(_pos.row, _pos.col);
      }
    }
    var getPos = function getPos(element, i) {
      var x, y;
      if (element.locked() || element.isParent()) {
        return false;
      }

      // see if we have a manual position set
      var rcPos = id2manPos[element.id()];
      if (rcPos) {
        x = rcPos.col * cellWidth + cellWidth / 2 + bb.x1;
        y = rcPos.row * cellHeight + cellHeight / 2 + bb.y1;
      } else {
        // otherwise set automatically

        while (used(row, col)) {
          moveToNextCell();
        }
        x = col * cellWidth + cellWidth / 2 + bb.x1;
        y = row * cellHeight + cellHeight / 2 + bb.y1;
        use(row, col);
        moveToNextCell();
      }
      return {
        x: x,
        y: y
      };
    };
    nodes.layoutPositions(this, options, getPos);
  }
  return this; // chaining
};

// default layout options
var defaults$2 = {
  ready: function ready() {},
  // on layoutready
  stop: function stop() {} // on layoutstop
};

// constructor
// options : object containing layout options
function NullLayout(options) {
  this.options = extend({}, defaults$2, options);
}

// runs the layout
NullLayout.prototype.run = function () {
  var options = this.options;
  var eles = options.eles; // elements to consider in the layout
  var layout = this;

  // cy is automatically populated for us in the constructor
  // (disable eslint for next line as this serves as example layout code to external developers)
  // eslint-disable-next-line no-unused-vars
  options.cy;
  layout.emit('layoutstart');

  // puts all nodes at (0, 0)
  // n.b. most layouts would use layoutPositions(), instead of positions() and manual events
  eles.nodes().positions(function () {
    return {
      x: 0,
      y: 0
    };
  });

  // trigger layoutready when each node has had its position set at least once
  layout.one('layoutready', options.ready);
  layout.emit('layoutready');

  // trigger layoutstop when the layout stops (e.g. finishes)
  layout.one('layoutstop', options.stop);
  layout.emit('layoutstop');
  return this; // chaining
};

// called on continuous layouts to stop them before they finish
NullLayout.prototype.stop = function () {
  return this; // chaining
};

var defaults$1 = {
  positions: undefined,
  // map of (node id) => (position obj); or function(node){ return somPos; }
  zoom: undefined,
  // the zoom level to set (prob want fit = false if set)
  pan: undefined,
  // the pan level to set (prob want fit = false if set)
  fit: true,
  // whether to fit to viewport
  padding: 30,
  // padding on fit
  spacingFactor: undefined,
  // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  animate: false,
  // whether to transition the node positions
  animationDuration: 500,
  // duration of animation in ms if enabled
  animationEasing: undefined,
  // easing of animation if enabled
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts
  ready: undefined,
  // callback on layoutready
  stop: undefined,
  // callback on layoutstop
  transform: function transform(node, position) {
    return position;
  } // transform a given node position. Useful for changing flow direction in discrete layouts
};
function PresetLayout(options) {
  this.options = extend({}, defaults$1, options);
}
PresetLayout.prototype.run = function () {
  var options = this.options;
  var eles = options.eles;
  var nodes = eles.nodes();
  var posIsFn = fn$6(options.positions);
  function getPosition(node) {
    if (options.positions == null) {
      return copyPosition(node.position());
    }
    if (posIsFn) {
      return options.positions(node);
    }
    var pos = options.positions[node._private.data.id];
    if (pos == null) {
      return null;
    }
    return pos;
  }
  nodes.layoutPositions(this, options, function (node, i) {
    var position = getPosition(node);
    if (node.locked() || position == null) {
      return false;
    }
    return position;
  });
  return this; // chaining
};

var defaults = {
  fit: true,
  // whether to fit to viewport
  padding: 30,
  // fit padding
  boundingBox: undefined,
  // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  animate: false,
  // whether to transition the node positions
  animationDuration: 500,
  // duration of animation in ms if enabled
  animationEasing: undefined,
  // easing of animation if enabled
  animateFilter: function animateFilter(node, i) {
    return true;
  },
  // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts
  ready: undefined,
  // callback on layoutready
  stop: undefined,
  // callback on layoutstop
  transform: function transform(node, position) {
    return position;
  } // transform a given node position. Useful for changing flow direction in discrete layouts 
};
function RandomLayout(options) {
  this.options = extend({}, defaults, options);
}
RandomLayout.prototype.run = function () {
  var options = this.options;
  var cy = options.cy;
  var eles = options.eles;
  var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
    x1: 0,
    y1: 0,
    w: cy.width(),
    h: cy.height()
  });
  var getPos = function getPos(node, i) {
    return {
      x: bb.x1 + Math.round(Math.random() * bb.w),
      y: bb.y1 + Math.round(Math.random() * bb.h)
    };
  };
  eles.nodes().layoutPositions(this, options, getPos);
  return this; // chaining
};

var layout = [{
  name: 'breadthfirst',
  impl: BreadthFirstLayout
}, {
  name: 'circle',
  impl: CircleLayout
}, {
  name: 'concentric',
  impl: ConcentricLayout
}, {
  name: 'cose',
  impl: CoseLayout
}, {
  name: 'grid',
  impl: GridLayout
}, {
  name: 'null',
  impl: NullLayout
}, {
  name: 'preset',
  impl: PresetLayout
}, {
  name: 'random',
  impl: RandomLayout
}];

function NullRenderer(options) {
  this.options = options;
  this.notifications = 0; // for testing
}
var noop = function noop() {};
var throwImgErr = function throwImgErr() {
  throw new Error('A headless instance can not render images');
};
NullRenderer.prototype = {
  recalculateRenderedStyle: noop,
  notify: function notify() {
    this.notifications++;
  },
  init: noop,
  isHeadless: function isHeadless() {
    return true;
  },
  png: throwImgErr,
  jpg: throwImgErr
};

var BRp$f = {};
BRp$f.arrowShapeWidth = 0.3;
BRp$f.registerArrowShapes = function () {
  var arrowShapes = this.arrowShapes = {};
  var renderer = this;

  // Contract for arrow shapes:
  // 0, 0 is arrow tip
  // (0, 1) is direction towards node
  // (1, 0) is right
  //
  // functional api:
  // collide: check x, y in shape
  // roughCollide: called before collide, no false negatives
  // draw: draw
  // spacing: dist(arrowTip, nodeBoundary)
  // gap: dist(edgeTip, nodeBoundary), edgeTip may != arrowTip

  var bbCollide = function bbCollide(x, y, size, angle, translation, edgeWidth, padding) {
    var x1 = translation.x - size / 2 - padding;
    var x2 = translation.x + size / 2 + padding;
    var y1 = translation.y - size / 2 - padding;
    var y2 = translation.y + size / 2 + padding;
    var inside = x1 <= x && x <= x2 && y1 <= y && y <= y2;
    return inside;
  };
  var transform = function transform(x, y, size, angle, translation) {
    var xRotated = x * Math.cos(angle) - y * Math.sin(angle);
    var yRotated = x * Math.sin(angle) + y * Math.cos(angle);
    var xScaled = xRotated * size;
    var yScaled = yRotated * size;
    var xTranslated = xScaled + translation.x;
    var yTranslated = yScaled + translation.y;
    return {
      x: xTranslated,
      y: yTranslated
    };
  };
  var transformPoints = function transformPoints(pts, size, angle, translation) {
    var retPts = [];
    for (var i = 0; i < pts.length; i += 2) {
      var x = pts[i];
      var y = pts[i + 1];
      retPts.push(transform(x, y, size, angle, translation));
    }
    return retPts;
  };
  var pointsToArr = function pointsToArr(pts) {
    var ret = [];
    for (var i = 0; i < pts.length; i++) {
      var p = pts[i];
      ret.push(p.x, p.y);
    }
    return ret;
  };
  var standardGap = function standardGap(edge) {
    return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;
  };
  var defineArrowShape = function defineArrowShape(name, defn) {
    if (string(defn)) {
      defn = arrowShapes[defn];
    }
    arrowShapes[name] = extend({
      name: name,
      points: [-0.15, -0.3, 0.15, -0.3, 0.15, 0.3, -0.15, 0.3],
      collide: function collide(x, y, size, angle, translation, padding) {
        var points = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
        var inside = pointInsidePolygonPoints(x, y, points);
        return inside;
      },
      roughCollide: bbCollide,
      draw: function draw(context, size, angle, translation) {
        var points = transformPoints(this.points, size, angle, translation);
        renderer.arrowShapeImpl('polygon')(context, points);
      },
      spacing: function spacing(edge) {
        return 0;
      },
      gap: standardGap
    }, defn);
  };
  defineArrowShape('none', {
    collide: falsify,
    roughCollide: falsify,
    draw: noop$1,
    spacing: zeroify,
    gap: zeroify
  });
  defineArrowShape('triangle', {
    points: [-0.15, -0.3, 0, 0, 0.15, -0.3]
  });
  defineArrowShape('arrow', 'triangle');
  defineArrowShape('triangle-backcurve', {
    points: arrowShapes['triangle'].points,
    controlPoint: [0, -0.15],
    roughCollide: bbCollide,
    draw: function draw(context, size, angle, translation, edgeWidth) {
      var ptsTrans = transformPoints(this.points, size, angle, translation);
      var ctrlPt = this.controlPoint;
      var ctrlPtTrans = transform(ctrlPt[0], ctrlPt[1], size, angle, translation);
      renderer.arrowShapeImpl(this.name)(context, ptsTrans, ctrlPtTrans);
    },
    gap: function gap(edge) {
      return standardGap(edge) * 0.8;
    }
  });
  defineArrowShape('triangle-tee', {
    points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
    pointsTee: [-0.15, -0.4, -0.15, -0.5, 0.15, -0.5, 0.15, -0.4],
    collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
      var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
      var teePts = pointsToArr(transformPoints(this.pointsTee, size + 2 * padding, angle, translation));
      var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
      return inside;
    },
    draw: function draw(context, size, angle, translation, edgeWidth) {
      var triPts = transformPoints(this.points, size, angle, translation);
      var teePts = transformPoints(this.pointsTee, size, angle, translation);
      renderer.arrowShapeImpl(this.name)(context, triPts, teePts);
    }
  });
  defineArrowShape('circle-triangle', {
    radius: 0.15,
    pointsTr: [0, -0.15, 0.15, -0.45, -0.15, -0.45, 0, -0.15],
    collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
      var t = translation;
      var circleInside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
      var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
      return pointInsidePolygonPoints(x, y, triPts) || circleInside;
    },
    draw: function draw(context, size, angle, translation, edgeWidth) {
      var triPts = transformPoints(this.pointsTr, size, angle, translation);
      renderer.arrowShapeImpl(this.name)(context, triPts, translation.x, translation.y, this.radius * size);
    },
    spacing: function spacing(edge) {
      return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
    }
  });
  defineArrowShape('triangle-cross', {
    points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
    baseCrossLinePts: [-0.15, -0.4,
    // first half of the rectangle
    -0.15, -0.4, 0.15, -0.4,
    // second half of the rectangle
    0.15, -0.4],
    crossLinePts: function crossLinePts(size, edgeWidth) {
      // shift points so that the distance between the cross points matches edge width
      var p = this.baseCrossLinePts.slice();
      var shiftFactor = edgeWidth / size;
      var y0 = 3;
      var y1 = 5;
      p[y0] = p[y0] - shiftFactor;
      p[y1] = p[y1] - shiftFactor;
      return p;
    },
    collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
      var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
      var teePts = pointsToArr(transformPoints(this.crossLinePts(size, edgeWidth), size + 2 * padding, angle, translation));
      var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
      return inside;
    },
    draw: function draw(context, size, angle, translation, edgeWidth) {
      var triPts = transformPoints(this.points, size, angle, translation);
      var crossLinePts = transformPoints(this.crossLinePts(size, edgeWidth), size, angle, translation);
      renderer.arrowShapeImpl(this.name)(context, triPts, crossLinePts);
    }
  });
  defineArrowShape('vee', {
    points: [-0.15, -0.3, 0, 0, 0.15, -0.3, 0, -0.15],
    gap: function gap(edge) {
      return standardGap(edge) * 0.525;
    }
  });
  defineArrowShape('circle', {
    radius: 0.15,
    collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
      var t = translation;
      var inside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
      return inside;
    },
    draw: function draw(context, size, angle, translation, edgeWidth) {
      renderer.arrowShapeImpl(this.name)(context, translation.x, translation.y, this.radius * size);
    },
    spacing: function spacing(edge) {
      return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
    }
  });
  defineArrowShape('tee', {
    points: [-0.15, 0, -0.15, -0.1, 0.15, -0.1, 0.15, 0],
    spacing: function spacing(edge) {
      return 1;
    },
    gap: function gap(edge) {
      return 1;
    }
  });
  defineArrowShape('square', {
    points: [-0.15, 0.00, 0.15, 0.00, 0.15, -0.3, -0.15, -0.3]
  });
  defineArrowShape('diamond', {
    points: [-0.15, -0.15, 0, -0.3, 0.15, -0.15, 0, 0],
    gap: function gap(edge) {
      return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
    }
  });
  defineArrowShape('chevron', {
    points: [0, 0, -0.15, -0.15, -0.1, -0.2, 0, -0.1, 0.1, -0.2, 0.15, -0.15],
    gap: function gap(edge) {
      return 0.95 * edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
    }
  });
};

var BRp$e = {};

// Project mouse
BRp$e.projectIntoViewport = function (clientX, clientY) {
  var cy = this.cy;
  var offsets = this.findContainerClientCoords();
  var offsetLeft = offsets[0];
  var offsetTop = offsets[1];
  var scale = offsets[4];
  var pan = cy.pan();
  var zoom = cy.zoom();
  var x = ((clientX - offsetLeft) / scale - pan.x) / zoom;
  var y = ((clientY - offsetTop) / scale - pan.y) / zoom;
  return [x, y];
};
BRp$e.findContainerClientCoords = function () {
  if (this.containerBB) {
    return this.containerBB;
  }
  var container = this.container;
  var rect = container.getBoundingClientRect();
  var style = this.cy.window().getComputedStyle(container);
  var styleValue = function styleValue(name) {
    return parseFloat(style.getPropertyValue(name));
  };
  var padding = {
    left: styleValue('padding-left'),
    right: styleValue('padding-right'),
    top: styleValue('padding-top'),
    bottom: styleValue('padding-bottom')
  };
  var border = {
    left: styleValue('border-left-width'),
    right: styleValue('border-right-width'),
    top: styleValue('border-top-width'),
    bottom: styleValue('border-bottom-width')
  };
  var clientWidth = container.clientWidth;
  var clientHeight = container.clientHeight;
  var paddingHor = padding.left + padding.right;
  var paddingVer = padding.top + padding.bottom;
  var borderHor = border.left + border.right;
  var scale = rect.width / (clientWidth + borderHor);
  var unscaledW = clientWidth - paddingHor;
  var unscaledH = clientHeight - paddingVer;
  var left = rect.left + padding.left + border.left;
  var top = rect.top + padding.top + border.top;
  return this.containerBB = [left, top, unscaledW, unscaledH, scale];
};
BRp$e.invalidateContainerClientCoordsCache = function () {
  this.containerBB = null;
};
BRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {
  return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];
};
BRp$e.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  var self = this;
  var r = this;
  var eles = r.getCachedZSortedEles();
  var near = []; // 1 node max, 1 edge max
  var zoom = r.cy.zoom();
  var hasCompounds = r.cy.hasCompoundNodes();
  var edgeThreshold = (isTouch ? 24 : 8) / zoom;
  var nodeThreshold = (isTouch ? 8 : 2) / zoom;
  var labelThreshold = (isTouch ? 8 : 2) / zoom;
  var minSqDist = Infinity;
  var nearEdge;
  var nearNode;
  if (interactiveElementsOnly) {
    eles = eles.interactive;
  }
  function addEle(ele, sqDist) {
    if (ele.isNode()) {
      if (nearNode) {
        return; // can't replace node
      } else {
        nearNode = ele;
        near.push(ele);
      }
    }
    if (ele.isEdge() && (sqDist == null || sqDist < minSqDist)) {
      if (nearEdge) {
        // then replace existing edge
        // can replace only if same z-index
        if (nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value && nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value) {
          for (var i = 0; i < near.length; i++) {
            if (near[i].isEdge()) {
              near[i] = ele;
              nearEdge = ele;
              minSqDist = sqDist != null ? sqDist : minSqDist;
              break;
            }
          }
        }
      } else {
        near.push(ele);
        nearEdge = ele;
        minSqDist = sqDist != null ? sqDist : minSqDist;
      }
    }
  }
  function checkNode(node) {
    var width = node.outerWidth() + 2 * nodeThreshold;
    var height = node.outerHeight() + 2 * nodeThreshold;
    var hw = width / 2;
    var hh = height / 2;
    var pos = node.position();
    var cornerRadius = node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue;
    var rs = node._private.rscratch;
    if (pos.x - hw <= x && x <= pos.x + hw // bb check x
    && pos.y - hh <= y && y <= pos.y + hh // bb check y
    ) {
      var shape = r.nodeShapes[self.getNodeShape(node)];
      if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y, cornerRadius, rs)) {
        addEle(node, 0);
        return true;
      }
    }
  }
  function checkEdge(edge) {
    var _p = edge._private;
    var rs = _p.rscratch;
    var styleWidth = edge.pstyle('width').pfValue;
    var scale = edge.pstyle('arrow-scale').value;
    var width = styleWidth / 2 + edgeThreshold; // more like a distance radius from centre
    var widthSq = width * width;
    var width2 = width * 2;
    var src = _p.source;
    var tgt = _p.target;
    var sqDist;
    if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {
      var pts = rs.allpts;
      for (var i = 0; i + 3 < pts.length; i += 2) {
        if (inLineVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], width2) && widthSq > (sqDist = sqdistToFiniteLine(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3]))) {
          addEle(edge, sqDist);
          return true;
        }
      }
    } else if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
      var pts = rs.allpts;
      for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
        if (inBezierVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5], width2) && widthSq > (sqDist = sqdistToQuadraticBezier(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5]))) {
          addEle(edge, sqDist);
          return true;
        }
      }
    }

    // if we're close to the edge but didn't hit it, maybe we hit its arrows

    var src = src || _p.source;
    var tgt = tgt || _p.target;
    var arSize = self.getArrowWidth(styleWidth, scale);
    var arrows = [{
      name: 'source',
      x: rs.arrowStartX,
      y: rs.arrowStartY,
      angle: rs.srcArrowAngle
    }, {
      name: 'target',
      x: rs.arrowEndX,
      y: rs.arrowEndY,
      angle: rs.tgtArrowAngle
    }, {
      name: 'mid-source',
      x: rs.midX,
      y: rs.midY,
      angle: rs.midsrcArrowAngle
    }, {
      name: 'mid-target',
      x: rs.midX,
      y: rs.midY,
      angle: rs.midtgtArrowAngle
    }];
    for (var i = 0; i < arrows.length; i++) {
      var ar = arrows[i];
      var shape = r.arrowShapes[edge.pstyle(ar.name + '-arrow-shape').value];
      var edgeWidth = edge.pstyle('width').pfValue;
      if (shape.roughCollide(x, y, arSize, ar.angle, {
        x: ar.x,
        y: ar.y
      }, edgeWidth, edgeThreshold) && shape.collide(x, y, arSize, ar.angle, {
        x: ar.x,
        y: ar.y
      }, edgeWidth, edgeThreshold)) {
        addEle(edge);
        return true;
      }
    }

    // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)
    if (hasCompounds && near.length > 0) {
      checkNode(src);
      checkNode(tgt);
    }
  }
  function preprop(obj, name, pre) {
    return getPrefixedProperty(obj, name, pre);
  }
  function checkLabel(ele, prefix) {
    var _p = ele._private;
    var th = labelThreshold;
    var prefixDash;
    if (prefix) {
      prefixDash = prefix + '-';
    } else {
      prefixDash = '';
    }
    ele.boundingBox();
    var bb = _p.labelBounds[prefix || 'main'];
    var text = ele.pstyle(prefixDash + 'label').value;
    var eventsEnabled = ele.pstyle('text-events').strValue === 'yes';
    if (!eventsEnabled || !text) {
      return;
    }
    var lx = preprop(_p.rscratch, 'labelX', prefix);
    var ly = preprop(_p.rscratch, 'labelY', prefix);
    var theta = preprop(_p.rscratch, 'labelAngle', prefix);
    var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
    var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
    var lx1 = bb.x1 - th - ox; // (-ox, -oy) as bb already includes margin
    var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)
    var ly1 = bb.y1 - th - oy;
    var ly2 = bb.y2 + th - oy;
    if (theta) {
      var cos = Math.cos(theta);
      var sin = Math.sin(theta);
      var rotate = function rotate(x, y) {
        x = x - lx;
        y = y - ly;
        return {
          x: x * cos - y * sin + lx,
          y: x * sin + y * cos + ly
        };
      };
      var px1y1 = rotate(lx1, ly1);
      var px1y2 = rotate(lx1, ly2);
      var px2y1 = rotate(lx2, ly1);
      var px2y2 = rotate(lx2, ly2);
      var points = [
      // with the margin added after the rotation is applied
      px1y1.x + ox, px1y1.y + oy, px2y1.x + ox, px2y1.y + oy, px2y2.x + ox, px2y2.y + oy, px1y2.x + ox, px1y2.y + oy];
      if (pointInsidePolygonPoints(x, y, points)) {
        addEle(ele);
        return true;
      }
    } else {
      // do a cheaper bb check
      if (inBoundingBox(bb, x, y)) {
        addEle(ele);
        return true;
      }
    }
  }
  for (var i = eles.length - 1; i >= 0; i--) {
    // reverse order for precedence
    var ele = eles[i];
    if (ele.isNode()) {
      checkNode(ele) || checkLabel(ele);
    } else {
      // then edge
      checkEdge(ele) || checkLabel(ele) || checkLabel(ele, 'source') || checkLabel(ele, 'target');
    }
  }
  return near;
};

// 'Give me everything from this box'
BRp$e.getAllInBox = function (x1, y1, x2, y2) {
  var eles = this.getCachedZSortedEles().interactive;
  var zoom = this.cy.zoom();
  var labelThreshold = 2 / zoom;
  var box = [];
  var x1c = Math.min(x1, x2);
  var x2c = Math.max(x1, x2);
  var y1c = Math.min(y1, y2);
  var y2c = Math.max(y1, y2);
  x1 = x1c;
  x2 = x2c;
  y1 = y1c;
  y2 = y2c;
  var boxBb = makeBoundingBox({
    x1: x1,
    y1: y1,
    x2: x2,
    y2: y2
  });
  var selectionBox = [{
    x: boxBb.x1,
    y: boxBb.y1
  }, {
    x: boxBb.x2,
    y: boxBb.y1
  }, {
    x: boxBb.x2,
    y: boxBb.y2
  }, {
    x: boxBb.x1,
    y: boxBb.y2
  }];
  var boxEdges = [[selectionBox[0], selectionBox[1]], [selectionBox[1], selectionBox[2]], [selectionBox[2], selectionBox[3]], [selectionBox[3], selectionBox[0]]];
  function preprop(obj, name, pre) {
    return getPrefixedProperty(obj, name, pre);
  }
  function getRotatedLabelBox(ele, prefix) {
    var _p = ele._private;
    var th = labelThreshold;
    var prefixDash = '';
    ele.boundingBox();
    var bb = _p.labelBounds['main'];

    // If the bounding box is not available, return null.
    // This indicates that the label box cannot be calculated, which is consistent
    // with the expected behavior of this function. Returning null allows the caller
    // to handle the absence of a bounding box explicitly.
    if (!bb) {
      return null;
    }
    var lx = preprop(_p.rscratch, 'labelX', prefix);
    var ly = preprop(_p.rscratch, 'labelY', prefix);
    var theta = preprop(_p.rscratch, 'labelAngle', prefix);
    var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
    var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
    var lx1 = bb.x1 - th - ox;
    var lx2 = bb.x2 + th - ox;
    var ly1 = bb.y1 - th - oy;
    var ly2 = bb.y2 + th - oy;
    if (theta) {
      var cos = Math.cos(theta);
      var sin = Math.sin(theta);
      var rotate = function rotate(x, y) {
        x = x - lx;
        y = y - ly;
        return {
          x: x * cos - y * sin + lx,
          y: x * sin + y * cos + ly
        };
      };
      return [rotate(lx1, ly1), rotate(lx2, ly1), rotate(lx2, ly2), rotate(lx1, ly2)];
    } else {
      return [{
        x: lx1,
        y: ly1
      }, {
        x: lx2,
        y: ly1
      }, {
        x: lx2,
        y: ly2
      }, {
        x: lx1,
        y: ly2
      }];
    }
  }
  function doLinesIntersect(p1, p2, q1, q2) {
    function ccw(a, b, c) {
      return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
    }
    return ccw(p1, q1, q2) !== ccw(p2, q1, q2) && ccw(p1, p2, q1) !== ccw(p1, p2, q2);
  }
  for (var e = 0; e < eles.length; e++) {
    var ele = eles[e];
    if (ele.isNode()) {
      var node = ele;
      var textEvents = node.pstyle('text-events').strValue === 'yes';
      var nodeBoxSelectMode = node.pstyle('box-selection').strValue;
      var labelBoxSelectEnabled = node.pstyle('box-select-labels').strValue === 'yes';
      if (nodeBoxSelectMode === 'none') {
        continue;
      }
      var includeLabels = (nodeBoxSelectMode === 'overlap' || labelBoxSelectEnabled) && textEvents;
      var nodeBb = node.boundingBox({
        includeNodes: true,
        includeEdges: false,
        includeLabels: includeLabels
      });
      if (nodeBoxSelectMode === 'contain') {
        var selected = false;
        if (labelBoxSelectEnabled && textEvents) {
          var rotatedLabelBox = getRotatedLabelBox(node);
          if (rotatedLabelBox && satPolygonIntersection(rotatedLabelBox, selectionBox)) {
            box.push(node);
            selected = true;
          }
        }
        if (!selected && boundingBoxInBoundingBox(boxBb, nodeBb)) {
          box.push(node);
        }
      } else if (nodeBoxSelectMode === 'overlap') {
        if (boundingBoxesIntersect(boxBb, nodeBb)) {
          var nodeBodyBb = node.boundingBox({
            includeNodes: true,
            includeEdges: true,
            includeLabels: false,
            includeMainLabels: false,
            includeSourceLabels: false,
            includeTargetLabels: false
          });
          var nodeBodyCorners = [{
            x: nodeBodyBb.x1,
            y: nodeBodyBb.y1
          }, {
            x: nodeBodyBb.x2,
            y: nodeBodyBb.y1
          }, {
            x: nodeBodyBb.x2,
            y: nodeBodyBb.y2
          }, {
            x: nodeBodyBb.x1,
            y: nodeBodyBb.y2
          }];

          // if node body intersects, no need to check label
          if (satPolygonIntersection(nodeBodyCorners, selectionBox)) {
            box.push(node);
          } else {
            // only check label if node body didn't intersect
            var _rotatedLabelBox = getRotatedLabelBox(node);
            if (_rotatedLabelBox && satPolygonIntersection(_rotatedLabelBox, selectionBox)) {
              box.push(node);
            }
          }
        }
      }
    } else {
      var edge = ele;
      var _p = edge._private;
      var rs = _p.rscratch;
      var edgeBoxSelectMode = edge.pstyle('box-selection').strValue;
      if (edgeBoxSelectMode === 'none') {
        continue;
      }
      if (edgeBoxSelectMode === 'contain') {
        if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {
          continue;
        }
        if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {
          continue;
        }
        if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound' || rs.edgeType === 'segments' || rs.edgeType === 'haystack') {
          var pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
          var allInside = true;
          for (var i = 0; i < pts.length; i++) {
            if (!pointInBoundingBox(boxBb, pts[i])) {
              allInside = false;
              break;
            }
          }
          if (allInside) {
            box.push(edge);
          }
        } else if (rs.edgeType === 'straight') {
          box.push(edge);
        }
      } else if (edgeBoxSelectMode === 'overlap') {
        var _selected = false;

        // Check: either endpoint inside box
        if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null && (inBoundingBox(boxBb, rs.startX, rs.startY) || inBoundingBox(boxBb, rs.endX, rs.endY))) {
          box.push(edge);
          _selected = true;
        }

        // Haystack fallback (only check if not already selected)
        else if (!_selected && rs.edgeType === 'haystack') {
          var haystackPts = _p.rstyle.haystackPts;
          for (var _i = 0; _i < haystackPts.length; _i++) {
            if (pointInBoundingBox(boxBb, haystackPts[_i])) {
              box.push(edge);
              _selected = true;
              break;
            }
          }
        }

        // Segment intersection check (only if not already selected)
        if (!_selected) {
          var _pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;

          // straight edges
          if ((!_pts || _pts.length < 2) && rs.edgeType === 'straight') {
            if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null) {
              _pts = [{
                x: rs.startX,
                y: rs.startY
              }, {
                x: rs.endX,
                y: rs.endY
              }];
            }
          }
          if (!_pts || _pts.length < 2) continue;
          for (var _i2 = 0; _i2 < _pts.length - 1; _i2++) {
            var segStart = _pts[_i2];
            var segEnd = _pts[_i2 + 1];
            for (var b = 0; b < boxEdges.length; b++) {
              var _boxEdges$b = _slicedToArray(boxEdges[b], 2),
                boxStart = _boxEdges$b[0],
                boxEnd = _boxEdges$b[1];
              if (doLinesIntersect(segStart, segEnd, boxStart, boxEnd)) {
                box.push(edge);
                _selected = true;
                break;
              }
            }
            if (_selected) break;
          }
        }
      }
    }
  }
  return box;
};

var BRp$d = {};
BRp$d.calculateArrowAngles = function (edge) {
  var rs = edge._private.rscratch;
  var isHaystack = rs.edgeType === 'haystack';
  var isBezier = rs.edgeType === 'bezier';
  var isMultibezier = rs.edgeType === 'multibezier';
  var isSegments = rs.edgeType === 'segments';
  var isCompound = rs.edgeType === 'compound';
  var isSelf = rs.edgeType === 'self';

  // Displacement gives direction for arrowhead orientation
  var dispX, dispY;
  var startX, startY, endX, endY, midX, midY;
  if (isHaystack) {
    startX = rs.haystackPts[0];
    startY = rs.haystackPts[1];
    endX = rs.haystackPts[2];
    endY = rs.haystackPts[3];
  } else {
    startX = rs.arrowStartX;
    startY = rs.arrowStartY;
    endX = rs.arrowEndX;
    endY = rs.arrowEndY;
  }
  midX = rs.midX;
  midY = rs.midY;

  // source
  //

  if (isSegments) {
    dispX = startX - rs.segpts[0];
    dispY = startY - rs.segpts[1];
  } else if (isMultibezier || isCompound || isSelf || isBezier) {
    var pts = rs.allpts;
    var bX = qbezierAt(pts[0], pts[2], pts[4], 0.1);
    var bY = qbezierAt(pts[1], pts[3], pts[5], 0.1);
    dispX = startX - bX;
    dispY = startY - bY;
  } else {
    dispX = startX - midX;
    dispY = startY - midY;
  }
  rs.srcArrowAngle = getAngleFromDisp(dispX, dispY);

  // mid target
  //

  var midX = rs.midX;
  var midY = rs.midY;
  if (isHaystack) {
    midX = (startX + endX) / 2;
    midY = (startY + endY) / 2;
  }
  dispX = endX - startX;
  dispY = endY - startY;
  if (isSegments) {
    var pts = rs.allpts;
    if (pts.length / 2 % 2 === 0) {
      var i2 = pts.length / 2;
      var i1 = i2 - 2;
      dispX = pts[i2] - pts[i1];
      dispY = pts[i2 + 1] - pts[i1 + 1];
    } else if (rs.isRound) {
      dispX = rs.midVector[1];
      dispY = -rs.midVector[0];
    } else {
      var i2 = pts.length / 2 - 1;
      var i1 = i2 - 2;
      dispX = pts[i2] - pts[i1];
      dispY = pts[i2 + 1] - pts[i1 + 1];
    }
  } else if (isMultibezier || isCompound || isSelf) {
    var pts = rs.allpts;
    var cpts = rs.ctrlpts;
    var bp0x, bp0y;
    var bp1x, bp1y;
    if (cpts.length / 2 % 2 === 0) {
      var p0 = pts.length / 2 - 1; // startpt
      var ic = p0 + 2;
      var p1 = ic + 2;
      bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0);
      bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0);
      bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0001);
      bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0001);
    } else {
      var ic = pts.length / 2 - 1; // ctrpt
      var p0 = ic - 2; // startpt
      var p1 = ic + 2; // endpt

      bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.4999);
      bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.4999);
      bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.5);
      bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.5);
    }
    dispX = bp1x - bp0x;
    dispY = bp1y - bp0y;
  }
  rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);
  rs.midDispX = dispX;
  rs.midDispY = dispY;

  // mid source
  //

  dispX *= -1;
  dispY *= -1;
  if (isSegments) {
    var pts = rs.allpts;
    if (pts.length / 2 % 2 === 0) ; else if (!rs.isRound) {
      var i2 = pts.length / 2 - 1;
      var i3 = i2 + 2;
      dispX = -(pts[i3] - pts[i2]);
      dispY = -(pts[i3 + 1] - pts[i2 + 1]);
    }
  }
  rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY);

  // target
  //

  if (isSegments) {
    dispX = endX - rs.segpts[rs.segpts.length - 2];
    dispY = endY - rs.segpts[rs.segpts.length - 1];
  } else if (isMultibezier || isCompound || isSelf || isBezier) {
    var pts = rs.allpts;
    var l = pts.length;
    var bX = qbezierAt(pts[l - 6], pts[l - 4], pts[l - 2], 0.9);
    var bY = qbezierAt(pts[l - 5], pts[l - 3], pts[l - 1], 0.9);
    dispX = endX - bX;
    dispY = endY - bY;
  } else {
    dispX = endX - midX;
    dispY = endY - midY;
  }
  rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);
};
BRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {
  var cache = this.arrowWidthCache = this.arrowWidthCache || {};
  var cachedVal = cache[edgeWidth + ', ' + scale];
  if (cachedVal) {
    return cachedVal;
  }
  cachedVal = Math.max(Math.pow(edgeWidth * 13.37, 0.9), 29) * scale;
  cache[edgeWidth + ', ' + scale] = cachedVal;
  return cachedVal;
};

/**
 * Explained by Blindman67 at https://stackoverflow.com/a/44856925/11028828
 */

// Declare reused variable to avoid reallocating variables every time the function is called
var x,
  y,
  v1 = {},
  v2 = {},
  sinA,
  sinA90,
  radDirection,
  drawDirection,
  angle,
  halfAngle,
  cRadius,
  lenOut,
  radius,
  limit;
var startX, startY, stopX, stopY;
var lastPoint;

// convert 2 points into vector form, polar form, and normalised
var asVec = function asVec(p, pp, v) {
  v.x = pp.x - p.x;
  v.y = pp.y - p.y;
  v.len = Math.sqrt(v.x * v.x + v.y * v.y);
  v.nx = v.x / v.len;
  v.ny = v.y / v.len;
  v.ang = Math.atan2(v.ny, v.nx);
};
var invertVec = function invertVec(originalV, invertedV) {
  invertedV.x = originalV.x * -1;
  invertedV.y = originalV.y * -1;
  invertedV.nx = originalV.nx * -1;
  invertedV.ny = originalV.ny * -1;
  invertedV.ang = originalV.ang > 0 ? -(Math.PI - originalV.ang) : Math.PI + originalV.ang;
};
var calcCornerArc = function calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius) {
  //-----------------------------------------
  // Part 1
  previousPoint !== lastPoint ? asVec(currentPoint, previousPoint, v1) : invertVec(v2, v1); // Avoid recalculating vec if it is the invert of the last one calculated
  asVec(currentPoint, nextPoint, v2);
  sinA = v1.nx * v2.ny - v1.ny * v2.nx;
  sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;
  angle = Math.asin(Math.max(-1, Math.min(1, sinA)));
  if (Math.abs(angle) < 1e-6) {
    x = currentPoint.x;
    y = currentPoint.y;
    cRadius = radius = 0;
    return;
  }
  //-----------------------------------------
  radDirection = 1;
  drawDirection = false;
  if (sinA90 < 0) {
    if (angle < 0) {
      angle = Math.PI + angle;
    } else {
      angle = Math.PI - angle;
      radDirection = -1;
      drawDirection = true;
    }
  } else {
    if (angle > 0) {
      radDirection = -1;
      drawDirection = true;
    }
  }
  if (currentPoint.radius !== undefined) {
    radius = currentPoint.radius;
  } else {
    radius = radiusMax;
  }
  //-----------------------------------------
  // Part 2
  halfAngle = angle / 2;
  //-----------------------------------------

  limit = Math.min(v1.len / 2, v2.len / 2);
  if (isArcRadius) {
    //-----------------------------------------
    // Part 3
    lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));

    //-----------------------------------------
    // Special part A
    if (lenOut > limit) {
      lenOut = limit;
      cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
    } else {
      cRadius = radius;
    }
  } else {
    lenOut = Math.min(limit, radius);
    cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  }
  //-----------------------------------------

  //-----------------------------------------
  // Part 4
  stopX = currentPoint.x + v2.nx * lenOut;
  stopY = currentPoint.y + v2.ny * lenOut;
  //-----------------------------------------
  // Part 5
  x = stopX - v2.ny * cRadius * radDirection;
  y = stopY + v2.nx * cRadius * radDirection;
  //-----------------------------------------
  // Additional Part : calculate start point E
  startX = currentPoint.x + v1.nx * lenOut;
  startY = currentPoint.y + v1.ny * lenOut;

  // Save last point to avoid recalculating vector when not needed
  lastPoint = currentPoint;
};

/**
 * Draw corner provided by {@link getRoundCorner}
 *
 * @param ctx :CanvasRenderingContext2D
 * @param roundCorner {{cx:number, cy:number, radius:number, endAngle: number, startAngle: number, counterClockwise: boolean}}
 */
function drawPreparedRoundCorner(ctx, roundCorner) {
  if (roundCorner.radius === 0) ctx.lineTo(roundCorner.cx, roundCorner.cy);else ctx.arc(roundCorner.cx, roundCorner.cy, roundCorner.radius, roundCorner.startAngle, roundCorner.endAngle, roundCorner.counterClockwise);
}

/**
 * Get round corner from a point and its previous and next neighbours in a path
 *
 * @param previousPoint {{x: number, y:number, radius: number?}}
 * @param currentPoint {{x: number, y:number, radius: number?}}
 * @param nextPoint {{x: number, y:number, radius: number?}}
 * @param radiusMax :number
 * @param isArcRadius :boolean
 * @return {{
 * cx:number, cy:number, radius:number,
 * startX:number, startY:number,
 * stopX:number, stopY: number,
 * endAngle: number, startAngle: number, counterClockwise: boolean
 * }}
 */
function getRoundCorner(previousPoint, currentPoint, nextPoint, radiusMax) {
  var isArcRadius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  if (radiusMax === 0 || currentPoint.radius === 0) return {
    cx: currentPoint.x,
    cy: currentPoint.y,
    radius: 0,
    startX: currentPoint.x,
    startY: currentPoint.y,
    stopX: currentPoint.x,
    stopY: currentPoint.y,
    startAngle: undefined,
    endAngle: undefined,
    counterClockwise: undefined
  };
  calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius);
  return {
    cx: x,
    cy: y,
    radius: cRadius,
    startX: startX,
    startY: startY,
    stopX: stopX,
    stopY: stopY,
    startAngle: v1.ang + Math.PI / 2 * radDirection,
    endAngle: v2.ang - Math.PI / 2 * radDirection,
    counterClockwise: drawDirection
  };
}

var AVOID_IMPOSSIBLE_BEZIER_CONSTANT = 0.01;
var AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L = Math.sqrt(2 * AVOID_IMPOSSIBLE_BEZIER_CONSTANT);
var BRp$c = {};
BRp$c.findMidptPtsEtc = function (edge, pairInfo) {
  var posPts = pairInfo.posPts,
    intersectionPts = pairInfo.intersectionPts,
    vectorNormInverse = pairInfo.vectorNormInverse;
  var midptPts;

  // n.b. assumes all edges in bezier bundle have same endpoints specified
  var srcManEndpt = edge.pstyle('source-endpoint');
  var tgtManEndpt = edge.pstyle('target-endpoint');
  var haveManualEndPts = srcManEndpt.units != null && tgtManEndpt.units != null;
  var recalcVectorNormInverse = function recalcVectorNormInverse(x1, y1, x2, y2) {
    var dy = y2 - y1;
    var dx = x2 - x1;
    var l = Math.sqrt(dx * dx + dy * dy);
    return {
      x: -dy / l,
      y: dx / l
    };
  };
  var edgeDistances = edge.pstyle('edge-distances').value;
  switch (edgeDistances) {
    case 'node-position':
      midptPts = posPts;
      break;
    case 'intersection':
      midptPts = intersectionPts;
      break;
    case 'endpoints':
      {
        if (haveManualEndPts) {
          var _this$manualEndptToPx = this.manualEndptToPx(edge.source()[0], srcManEndpt),
            _this$manualEndptToPx2 = _slicedToArray(_this$manualEndptToPx, 2),
            x1 = _this$manualEndptToPx2[0],
            y1 = _this$manualEndptToPx2[1];
          var _this$manualEndptToPx3 = this.manualEndptToPx(edge.target()[0], tgtManEndpt),
            _this$manualEndptToPx4 = _slicedToArray(_this$manualEndptToPx3, 2),
            x2 = _this$manualEndptToPx4[0],
            y2 = _this$manualEndptToPx4[1];
          var endPts = {
            x1: x1,
            y1: y1,
            x2: x2,
            y2: y2
          };
          vectorNormInverse = recalcVectorNormInverse(x1, y1, x2, y2);
          midptPts = endPts;
        } else {
          warn("Edge ".concat(edge.id(), " has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint.  Falling back on edge-distances:intersection (default)."));
          midptPts = intersectionPts; // back to default
        }
        break;
      }
  }
  return {
    midptPts: midptPts,
    vectorNormInverse: vectorNormInverse
  };
};
BRp$c.findHaystackPoints = function (edges) {
  for (var i = 0; i < edges.length; i++) {
    var edge = edges[i];
    var _p = edge._private;
    var rs = _p.rscratch;
    if (!rs.haystack) {
      var angle = Math.random() * 2 * Math.PI;
      rs.source = {
        x: Math.cos(angle),
        y: Math.sin(angle)
      };
      angle = Math.random() * 2 * Math.PI;
      rs.target = {
        x: Math.cos(angle),
        y: Math.sin(angle)
      };
    }
    var src = _p.source;
    var tgt = _p.target;
    var srcPos = src.position();
    var tgtPos = tgt.position();
    var srcW = src.width();
    var tgtW = tgt.width();
    var srcH = src.height();
    var tgtH = tgt.height();
    var radius = edge.pstyle('haystack-radius').value;
    var halfRadius = radius / 2; // b/c have to half width/height

    rs.haystackPts = rs.allpts = [rs.source.x * srcW * halfRadius + srcPos.x, rs.source.y * srcH * halfRadius + srcPos.y, rs.target.x * tgtW * halfRadius + tgtPos.x, rs.target.y * tgtH * halfRadius + tgtPos.y];
    rs.midX = (rs.allpts[0] + rs.allpts[2]) / 2;
    rs.midY = (rs.allpts[1] + rs.allpts[3]) / 2;

    // always override as haystack in case set to different type previously
    rs.edgeType = 'haystack';
    rs.haystack = true;
    this.storeEdgeProjections(edge);
    this.calculateArrowAngles(edge);
    this.recalculateEdgeLabelProjections(edge);
    this.calculateLabelAngles(edge);
  }
};
BRp$c.findSegmentsPoints = function (edge, pairInfo) {
  // Segments (multiple straight lines)

  var rs = edge._private.rscratch;
  var segmentWs = edge.pstyle('segment-weights');
  var segmentDs = edge.pstyle('segment-distances');
  var segmentRs = edge.pstyle('segment-radii');
  var segmentTs = edge.pstyle('radius-type');
  var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);
  var lastRadius = segmentRs.pfValue[segmentRs.pfValue.length - 1];
  var lastRadiusType = segmentTs.pfValue[segmentTs.pfValue.length - 1];
  rs.edgeType = 'segments';
  rs.segpts = [];
  rs.radii = [];
  rs.isArcRadius = [];
  for (var s = 0; s < segmentsN; s++) {
    var w = segmentWs.pfValue[s];
    var d = segmentDs.pfValue[s];
    var w1 = 1 - w;
    var w2 = w;
    var _this$findMidptPtsEtc = this.findMidptPtsEtc(edge, pairInfo),
      midptPts = _this$findMidptPtsEtc.midptPts,
      vectorNormInverse = _this$findMidptPtsEtc.vectorNormInverse;
    var adjustedMidpt = {
      x: midptPts.x1 * w1 + midptPts.x2 * w2,
      y: midptPts.y1 * w1 + midptPts.y2 * w2
    };
    rs.segpts.push(adjustedMidpt.x + vectorNormInverse.x * d, adjustedMidpt.y + vectorNormInverse.y * d);
    rs.radii.push(segmentRs.pfValue[s] !== undefined ? segmentRs.pfValue[s] : lastRadius);
    rs.isArcRadius.push((segmentTs.pfValue[s] !== undefined ? segmentTs.pfValue[s] : lastRadiusType) === 'arc-radius');
  }
};
BRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  // Self-edge

  var rs = edge._private.rscratch;
  var dirCounts = pairInfo.dirCounts,
    srcPos = pairInfo.srcPos;
  var ctrlptDists = edge.pstyle('control-point-distances');
  var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  var loopDir = edge.pstyle('loop-direction').pfValue;
  var loopSwp = edge.pstyle('loop-sweep').pfValue;
  var stepSize = edge.pstyle('control-point-step-size').pfValue;
  rs.edgeType = 'self';
  var j = i;
  var loopDist = stepSize;
  if (edgeIsUnbundled) {
    j = 0;
    loopDist = ctrlptDist;
  }
  var loopAngle = loopDir - Math.PI / 2;
  var outAngle = loopAngle - loopSwp / 2;
  var inAngle = loopAngle + loopSwp / 2;

  // increase by step size for overlapping loops, keyed on direction and sweep values
  var dc = String(loopDir + '_' + loopSwp);
  j = dirCounts[dc] === undefined ? dirCounts[dc] = 0 : ++dirCounts[dc];
  rs.ctrlpts = [srcPos.x + Math.cos(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.x + Math.cos(inAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(inAngle) * 1.4 * loopDist * (j / 3 + 1)];
};
BRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  // Compound edge

  var rs = edge._private.rscratch;
  rs.edgeType = 'compound';
  var srcPos = pairInfo.srcPos,
    tgtPos = pairInfo.tgtPos,
    srcW = pairInfo.srcW,
    srcH = pairInfo.srcH,
    tgtW = pairInfo.tgtW,
    tgtH = pairInfo.tgtH;
  var stepSize = edge.pstyle('control-point-step-size').pfValue;
  var ctrlptDists = edge.pstyle('control-point-distances');
  var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  var j = i;
  var loopDist = stepSize;
  if (edgeIsUnbundled) {
    j = 0;
    loopDist = ctrlptDist;
  }
  var loopW = 50;
  var loopaPos = {
    x: srcPos.x - srcW / 2,
    y: srcPos.y - srcH / 2
  };
  var loopbPos = {
    x: tgtPos.x - tgtW / 2,
    y: tgtPos.y - tgtH / 2
  };
  var loopPos = {
    x: Math.min(loopaPos.x, loopbPos.x),
    y: Math.min(loopaPos.y, loopbPos.y)
  };

  // avoids cases with impossible beziers
  var minCompoundStretch = 0.5;
  var compoundStretchA = Math.max(minCompoundStretch, Math.log(srcW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  var compoundStretchB = Math.max(minCompoundStretch, Math.log(tgtW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  rs.ctrlpts = [loopPos.x, loopPos.y - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchA, loopPos.x - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchB, loopPos.y];
};
BRp$c.findStraightEdgePoints = function (edge) {
  // Straight edge within bundle

  edge._private.rscratch.edgeType = 'straight';
};
BRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {
  var rs = edge._private.rscratch;
  var stepSize = edge.pstyle('control-point-step-size').pfValue;
  var ctrlptDists = edge.pstyle('control-point-distances');
  var ctrlptWs = edge.pstyle('control-point-weights');
  var bezierN = ctrlptDists && ctrlptWs ? Math.min(ctrlptDists.value.length, ctrlptWs.value.length) : 1;
  var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  var ctrlptWeight = ctrlptWs.value[0];

  // (Multi)bezier

  var multi = edgeIsUnbundled;
  rs.edgeType = multi ? 'multibezier' : 'bezier';
  rs.ctrlpts = [];
  for (var b = 0; b < bezierN; b++) {
    var normctrlptDist = (0.5 - pairInfo.eles.length / 2 + i) * stepSize * (edgeIsSwapped ? -1 : 1);
    var manctrlptDist = undefined;
    var sign = signum(normctrlptDist);
    if (multi) {
      ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size
      ctrlptWeight = ctrlptWs.value[b];
    }
    if (edgeIsUnbundled) {
      // multi or single unbundled
      manctrlptDist = ctrlptDist;
    } else {
      manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;
    }
    var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;
    var w1 = 1 - ctrlptWeight;
    var w2 = ctrlptWeight;
    var _this$findMidptPtsEtc2 = this.findMidptPtsEtc(edge, pairInfo),
      midptPts = _this$findMidptPtsEtc2.midptPts,
      vectorNormInverse = _this$findMidptPtsEtc2.vectorNormInverse;
    var adjustedMidpt = {
      x: midptPts.x1 * w1 + midptPts.x2 * w2,
      y: midptPts.y1 * w1 + midptPts.y2 * w2
    };
    rs.ctrlpts.push(adjustedMidpt.x + vectorNormInverse.x * distanceFromMidpoint, adjustedMidpt.y + vectorNormInverse.y * distanceFromMidpoint);
  }
};
BRp$c.findTaxiPoints = function (edge, pairInfo) {
  // Taxicab geometry with two turns maximum

  var rs = edge._private.rscratch;
  rs.edgeType = 'segments';
  var VERTICAL = 'vertical';
  var HORIZONTAL = 'horizontal';
  var LEFTWARD = 'leftward';
  var RIGHTWARD = 'rightward';
  var DOWNWARD = 'downward';
  var UPWARD = 'upward';
  var AUTO = 'auto';
  var posPts = pairInfo.posPts,
    srcW = pairInfo.srcW,
    srcH = pairInfo.srcH,
    tgtW = pairInfo.tgtW,
    tgtH = pairInfo.tgtH;
  var edgeDistances = edge.pstyle('edge-distances').value;
  var dIncludesNodeBody = edgeDistances !== 'node-position';
  var taxiDir = edge.pstyle('taxi-direction').value;
  var rawTaxiDir = taxiDir; // unprocessed value
  var taxiTurn = edge.pstyle('taxi-turn');
  var turnIsPercent = taxiTurn.units === '%';
  var taxiTurnPfVal = taxiTurn.pfValue;
  var turnIsNegative = taxiTurnPfVal < 0; // i.e. from target side
  var minD = edge.pstyle('taxi-turn-min-distance').pfValue;
  var dw = dIncludesNodeBody ? (srcW + tgtW) / 2 : 0;
  var dh = dIncludesNodeBody ? (srcH + tgtH) / 2 : 0;
  var pdx = posPts.x2 - posPts.x1;
  var pdy = posPts.y2 - posPts.y1;

  // take away the effective w/h from the magnitude of the delta value
  var subDWH = function subDWH(dxy, dwh) {
    if (dxy > 0) {
      return Math.max(dxy - dwh, 0);
    } else {
      return Math.min(dxy + dwh, 0);
    }
  };
  var dx = subDWH(pdx, dw);
  var dy = subDWH(pdy, dh);
  var isExplicitDir = false;
  if (rawTaxiDir === AUTO) {
    taxiDir = Math.abs(dx) > Math.abs(dy) ? HORIZONTAL : VERTICAL;
  } else if (rawTaxiDir === UPWARD || rawTaxiDir === DOWNWARD) {
    taxiDir = VERTICAL;
    isExplicitDir = true;
  } else if (rawTaxiDir === LEFTWARD || rawTaxiDir === RIGHTWARD) {
    taxiDir = HORIZONTAL;
    isExplicitDir = true;
  }
  var isVert = taxiDir === VERTICAL;
  var l = isVert ? dy : dx;
  var pl = isVert ? pdy : pdx;
  var sgnL = signum(pl);
  var forcedDir = false;
  if (!(isExplicitDir && (turnIsPercent || turnIsNegative)) // forcing in this case would cause weird growing in the opposite direction
  && (rawTaxiDir === DOWNWARD && pl < 0 || rawTaxiDir === UPWARD && pl > 0 || rawTaxiDir === LEFTWARD && pl > 0 || rawTaxiDir === RIGHTWARD && pl < 0)) {
    sgnL *= -1;
    l = sgnL * Math.abs(l);
    forcedDir = true;
  }
  var d;
  if (turnIsPercent) {
    var p = taxiTurnPfVal < 0 ? 1 + taxiTurnPfVal : taxiTurnPfVal;
    d = p * l;
  } else {
    var k = taxiTurnPfVal < 0 ? l : 0;
    d = k + taxiTurnPfVal * sgnL;
  }
  var getIsTooClose = function getIsTooClose(d) {
    return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);
  };
  var isTooCloseSrc = getIsTooClose(d);
  var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));
  var isTooClose = isTooCloseSrc || isTooCloseTgt;
  if (isTooClose && !forcedDir) {
    // non-ideal routing
    if (isVert) {
      // vertical fallbacks
      var lShapeInsideSrc = Math.abs(pl) <= srcH / 2;
      var lShapeInsideTgt = Math.abs(pdx) <= tgtW / 2;
      if (lShapeInsideSrc) {
        // horizontal Z-shape (direction not respected)
        var x = (posPts.x1 + posPts.x2) / 2;
        var y1 = posPts.y1,
          y2 = posPts.y2;
        rs.segpts = [x, y1, x, y2];
      } else if (lShapeInsideTgt) {
        // vertical Z-shape (distance not respected)
        var y = (posPts.y1 + posPts.y2) / 2;
        var x1 = posPts.x1,
          x2 = posPts.x2;
        rs.segpts = [x1, y, x2, y];
      } else {
        // L-shape fallback (turn distance not respected, but works well with tree siblings)
        rs.segpts = [posPts.x1, posPts.y2];
      }
    } else {
      // horizontal fallbacks
      var _lShapeInsideSrc = Math.abs(pl) <= srcW / 2;
      var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;
      if (_lShapeInsideSrc) {
        // vertical Z-shape (direction not respected)
        var _y = (posPts.y1 + posPts.y2) / 2;
        var _x = posPts.x1,
          _x2 = posPts.x2;
        rs.segpts = [_x, _y, _x2, _y];
      } else if (_lShapeInsideTgt) {
        // horizontal Z-shape (turn distance not respected)
        var _x3 = (posPts.x1 + posPts.x2) / 2;
        var _y2 = posPts.y1,
          _y3 = posPts.y2;
        rs.segpts = [_x3, _y2, _x3, _y3];
      } else {
        // L-shape (turn distance not respected, but works well for tree siblings)
        rs.segpts = [posPts.x2, posPts.y1];
      }
    }
  } else {
    // ideal routing
    if (isVert) {
      var _y4 = posPts.y1 + d + (dIncludesNodeBody ? srcH / 2 * sgnL : 0);
      var _x4 = posPts.x1,
        _x5 = posPts.x2;
      rs.segpts = [_x4, _y4, _x5, _y4];
    } else {
      // horizontal
      var _x6 = posPts.x1 + d + (dIncludesNodeBody ? srcW / 2 * sgnL : 0);
      var _y5 = posPts.y1,
        _y6 = posPts.y2;
      rs.segpts = [_x6, _y5, _x6, _y6];
    }
  }
  if (rs.isRound) {
    var radius = edge.pstyle('taxi-radius').value;
    var isArcRadius = edge.pstyle('radius-type').value[0] === 'arc-radius';
    rs.radii = new Array(rs.segpts.length / 2).fill(radius);
    rs.isArcRadius = new Array(rs.segpts.length / 2).fill(isArcRadius);
  }
};
BRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {
  var rs = edge._private.rscratch;

  // can only correct beziers for now...
  if (rs.edgeType === 'bezier') {
    var srcPos = pairInfo.srcPos,
      tgtPos = pairInfo.tgtPos,
      srcW = pairInfo.srcW,
      srcH = pairInfo.srcH,
      tgtW = pairInfo.tgtW,
      tgtH = pairInfo.tgtH,
      srcShape = pairInfo.srcShape,
      tgtShape = pairInfo.tgtShape,
      srcCornerRadius = pairInfo.srcCornerRadius,
      tgtCornerRadius = pairInfo.tgtCornerRadius,
      srcRs = pairInfo.srcRs,
      tgtRs = pairInfo.tgtRs;
    var badStart = !number$1(rs.startX) || !number$1(rs.startY);
    var badAStart = !number$1(rs.arrowStartX) || !number$1(rs.arrowStartY);
    var badEnd = !number$1(rs.endX) || !number$1(rs.endY);
    var badAEnd = !number$1(rs.arrowEndX) || !number$1(rs.arrowEndY);
    var minCpADistFactor = 3;
    var arrowW = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
    var minCpADist = minCpADistFactor * arrowW;
    var startACpDist = dist({
      x: rs.ctrlpts[0],
      y: rs.ctrlpts[1]
    }, {
      x: rs.startX,
      y: rs.startY
    });
    var closeStartACp = startACpDist < minCpADist;
    var endACpDist = dist({
      x: rs.ctrlpts[0],
      y: rs.ctrlpts[1]
    }, {
      x: rs.endX,
      y: rs.endY
    });
    var closeEndACp = endACpDist < minCpADist;
    var overlapping = false;
    if (badStart || badAStart || closeStartACp) {
      overlapping = true;

      // project control point along line from src centre to outside the src shape
      // (otherwise intersection will yield nothing)
      var cpD = {
        // delta
        x: rs.ctrlpts[0] - srcPos.x,
        y: rs.ctrlpts[1] - srcPos.y
      };
      var cpL = Math.sqrt(cpD.x * cpD.x + cpD.y * cpD.y); // length of line
      var cpM = {
        // normalised delta
        x: cpD.x / cpL,
        y: cpD.y / cpL
      };
      var radius = Math.max(srcW, srcH);
      var cpProj = {
        // *2 radius guarantees outside shape
        x: rs.ctrlpts[0] + cpM.x * 2 * radius,
        y: rs.ctrlpts[1] + cpM.y * 2 * radius
      };
      var srcCtrlPtIntn = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, cpProj.x, cpProj.y, 0, srcCornerRadius, srcRs);
      if (closeStartACp) {
        rs.ctrlpts[0] = rs.ctrlpts[0] + cpM.x * (minCpADist - startACpDist);
        rs.ctrlpts[1] = rs.ctrlpts[1] + cpM.y * (minCpADist - startACpDist);
      } else {
        rs.ctrlpts[0] = srcCtrlPtIntn[0] + cpM.x * minCpADist;
        rs.ctrlpts[1] = srcCtrlPtIntn[1] + cpM.y * minCpADist;
      }
    }
    if (badEnd || badAEnd || closeEndACp) {
      overlapping = true;

      // project control point along line from tgt centre to outside the tgt shape
      // (otherwise intersection will yield nothing)
      var _cpD = {
        // delta
        x: rs.ctrlpts[0] - tgtPos.x,
        y: rs.ctrlpts[1] - tgtPos.y
      };
      var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line
      var _cpM = {
        // normalised delta
        x: _cpD.x / _cpL,
        y: _cpD.y / _cpL
      };
      var _radius = Math.max(srcW, srcH);
      var _cpProj = {
        // *2 radius guarantees outside shape
        x: rs.ctrlpts[0] + _cpM.x * 2 * _radius,
        y: rs.ctrlpts[1] + _cpM.y * 2 * _radius
      };
      var tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0, tgtCornerRadius, tgtRs);
      if (closeEndACp) {
        rs.ctrlpts[0] = rs.ctrlpts[0] + _cpM.x * (minCpADist - endACpDist);
        rs.ctrlpts[1] = rs.ctrlpts[1] + _cpM.y * (minCpADist - endACpDist);
      } else {
        rs.ctrlpts[0] = tgtCtrlPtIntn[0] + _cpM.x * minCpADist;
        rs.ctrlpts[1] = tgtCtrlPtIntn[1] + _cpM.y * minCpADist;
      }
    }
    if (overlapping) {
      // recalc endpts
      this.findEndpoints(edge);
    }
  }
};
BRp$c.storeAllpts = function (edge) {
  var rs = edge._private.rscratch;
  if (rs.edgeType === 'multibezier' || rs.edgeType === 'bezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
    rs.allpts = [];
    rs.allpts.push(rs.startX, rs.startY);
    for (var b = 0; b + 1 < rs.ctrlpts.length; b += 2) {
      // ctrl pt itself
      rs.allpts.push(rs.ctrlpts[b], rs.ctrlpts[b + 1]);

      // the midpt between ctrlpts as intermediate destination pts
      if (b + 3 < rs.ctrlpts.length) {
        rs.allpts.push((rs.ctrlpts[b] + rs.ctrlpts[b + 2]) / 2, (rs.ctrlpts[b + 1] + rs.ctrlpts[b + 3]) / 2);
      }
    }
    rs.allpts.push(rs.endX, rs.endY);
    var m, mt;
    if (rs.ctrlpts.length / 2 % 2 === 0) {
      m = rs.allpts.length / 2 - 1;
      rs.midX = rs.allpts[m];
      rs.midY = rs.allpts[m + 1];
    } else {
      m = rs.allpts.length / 2 - 3;
      mt = 0.5;
      rs.midX = qbezierAt(rs.allpts[m], rs.allpts[m + 2], rs.allpts[m + 4], mt);
      rs.midY = qbezierAt(rs.allpts[m + 1], rs.allpts[m + 3], rs.allpts[m + 5], mt);
    }
  } else if (rs.edgeType === 'straight') {
    // need to calc these after endpts
    rs.allpts = [rs.startX, rs.startY, rs.endX, rs.endY];

    // default midpt for labels etc
    rs.midX = (rs.startX + rs.endX + rs.arrowStartX + rs.arrowEndX) / 4;
    rs.midY = (rs.startY + rs.endY + rs.arrowStartY + rs.arrowEndY) / 4;
  } else if (rs.edgeType === 'segments') {
    rs.allpts = [];
    rs.allpts.push(rs.startX, rs.startY);
    rs.allpts.push.apply(rs.allpts, rs.segpts);
    rs.allpts.push(rs.endX, rs.endY);
    if (rs.isRound) {
      rs.roundCorners = [];
      for (var i = 2; i + 3 < rs.allpts.length; i += 2) {
        var radius = rs.radii[i / 2 - 1];
        var isArcRadius = rs.isArcRadius[i / 2 - 1];
        rs.roundCorners.push(getRoundCorner({
          x: rs.allpts[i - 2],
          y: rs.allpts[i - 1]
        }, {
          x: rs.allpts[i],
          y: rs.allpts[i + 1],
          radius: radius
        }, {
          x: rs.allpts[i + 2],
          y: rs.allpts[i + 3]
        }, radius, isArcRadius));
      }
    }
    if (rs.segpts.length % 4 === 0) {
      var i2 = rs.segpts.length / 2;
      var i1 = i2 - 2;
      rs.midX = (rs.segpts[i1] + rs.segpts[i2]) / 2;
      rs.midY = (rs.segpts[i1 + 1] + rs.segpts[i2 + 1]) / 2;
    } else {
      var _i = rs.segpts.length / 2 - 1;
      if (!rs.isRound) {
        rs.midX = rs.segpts[_i];
        rs.midY = rs.segpts[_i + 1];
      } else {
        var point = {
          x: rs.segpts[_i],
          y: rs.segpts[_i + 1]
        };
        var corner = rs.roundCorners[_i / 2];
        if (corner.radius === 0) {
          // On collinear points
          var nextPoint = {
            x: rs.segpts[_i + 2],
            y: rs.segpts[_i + 3]
          };
          rs.midX = point.x;
          rs.midY = point.y;
          rs.midVector = [point.y - nextPoint.y, nextPoint.x - point.x];
        } else {
          // On rounded points
          var v = [point.x - corner.cx, point.y - corner.cy];
          var factor = corner.radius / Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));
          v = v.map(function (c) {
            return c * factor;
          });
          rs.midX = corner.cx + v[0];
          rs.midY = corner.cy + v[1];
          rs.midVector = v;
        }
      }
    }
  }
};
BRp$c.checkForInvalidEdgeWarning = function (edge) {
  var rs = edge[0]._private.rscratch;
  if (rs.nodesOverlap || number$1(rs.startX) && number$1(rs.startY) && number$1(rs.endX) && number$1(rs.endY)) {
    rs.loggedErr = false;
  } else {
    if (!rs.loggedErr) {
      rs.loggedErr = true;
      warn('Edge `' + edge.id() + '` has invalid endpoints and so it is impossible to draw.  Adjust your edge style (e.g. control points) accordingly or use an alternative edge type.  This is expected behaviour when the source node and the target node overlap.');
    }
  }
};
BRp$c.findEdgeControlPoints = function (edges) {
  var _this = this;
  if (!edges || edges.length === 0) {
    return;
  }
  var r = this;
  var cy = r.cy;
  var hasCompounds = cy.hasCompoundNodes();
  var hashTable = new Map$1();
  var getKey = function getKey(pairId, edgeIsUnbundled) {
    return [].concat(_toConsumableArray(pairId), [edgeIsUnbundled ? 1 : 0]).join('-');
  };
  var pairIds = [];
  var haystackEdges = [];

  // create a table of edge (src, tgt) => list of edges between them
  for (var i = 0; i < edges.length; i++) {
    var edge = edges[i];
    var _p = edge._private;
    var curveStyle = edge.pstyle('curve-style').value;

    // ignore edges who are not to be displayed
    // they shouldn't take up space
    if (edge.removed() || !edge.takesUpSpace()) {
      continue;
    }
    if (curveStyle === 'haystack') {
      haystackEdges.push(edge);
      continue;
    }
    var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || curveStyle === 'straight' || curveStyle === 'straight-triangle' || endsWith(curveStyle, 'taxi');
    var edgeIsBezier = curveStyle === 'unbundled-bezier' || curveStyle === 'bezier';
    var src = _p.source;
    var tgt = _p.target;
    var srcIndex = src.poolIndex();
    var tgtIndex = tgt.poolIndex();
    var pairId = [srcIndex, tgtIndex].sort();
    var key = getKey(pairId, edgeIsUnbundled);
    var tableEntry = hashTable.get(key);
    if (tableEntry == null) {
      tableEntry = {
        eles: []
      };
      pairIds.push({
        pairId: pairId,
        edgeIsUnbundled: edgeIsUnbundled
      });
      hashTable.set(key, tableEntry);
    }
    tableEntry.eles.push(edge);
    if (edgeIsUnbundled) {
      tableEntry.hasUnbundled = true;
    }
    if (edgeIsBezier) {
      tableEntry.hasBezier = true;
    }
  }

  // for each pair (src, tgt), create the ctrl pts
  // Nested for loop is OK; total number of iterations for both loops = edgeCount
  var _loop = function _loop() {
    var _pairIds$p = pairIds[p],
      pairId = _pairIds$p.pairId,
      edgeIsUnbundled = _pairIds$p.edgeIsUnbundled;
    var key = getKey(pairId, edgeIsUnbundled);
    var pairInfo = hashTable.get(key);
    var swappedpairInfo;
    if (!pairInfo.hasUnbundled) {
      var pllEdges = pairInfo.eles[0].parallelEdges().filter(function (e) {
        return e.isBundledBezier();
      });
      clearArray(pairInfo.eles);
      pllEdges.forEach(function (edge) {
        return pairInfo.eles.push(edge);
      });

      // for each pair id, the edges should be sorted by index
      pairInfo.eles.sort(function (edge1, edge2) {
        return edge1.poolIndex() - edge2.poolIndex();
      });
    }
    var firstEdge = pairInfo.eles[0];
    var src = firstEdge.source();
    var tgt = firstEdge.target();

    // make sure src/tgt distinction is consistent w.r.t. pairId
    if (src.poolIndex() > tgt.poolIndex()) {
      var temp = src;
      src = tgt;
      tgt = temp;
    }
    var srcPos = pairInfo.srcPos = src.position();
    var tgtPos = pairInfo.tgtPos = tgt.position();
    var srcW = pairInfo.srcW = src.outerWidth();
    var srcH = pairInfo.srcH = src.outerHeight();
    var tgtW = pairInfo.tgtW = tgt.outerWidth();
    var tgtH = pairInfo.tgtH = tgt.outerHeight();
    var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];
    var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];
    var srcCornerRadius = pairInfo.srcCornerRadius = src.pstyle('corner-radius').value === 'auto' ? 'auto' : src.pstyle('corner-radius').pfValue;
    var tgtCornerRadius = pairInfo.tgtCornerRadius = tgt.pstyle('corner-radius').value === 'auto' ? 'auto' : tgt.pstyle('corner-radius').pfValue;
    var tgtRs = pairInfo.tgtRs = tgt._private.rscratch;
    var srcRs = pairInfo.srcRs = src._private.rscratch;
    pairInfo.dirCounts = {
      'north': 0,
      'west': 0,
      'south': 0,
      'east': 0,
      'northwest': 0,
      'southwest': 0,
      'northeast': 0,
      'southeast': 0
    };
    for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {
      var _edge = pairInfo.eles[_i2];
      var rs = _edge[0]._private.rscratch;
      var _curveStyle = _edge.pstyle('curve-style').value;
      var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || endsWith(_curveStyle, 'segments') || endsWith(_curveStyle, 'taxi');

      // whether the normalised pair order is the reverse of the edge's src-tgt order
      var edgeIsSwapped = !src.same(_edge.source());
      if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {
        pairInfo.calculatedIntersection = true;

        // pt outside src shape to calc distance/displacement from src to tgt
        var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0, srcCornerRadius, srcRs);
        var srcIntn = pairInfo.srcIntn = srcOutside;

        // pt outside tgt shape to calc distance/displacement from src to tgt
        var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0, tgtCornerRadius, tgtRs);
        var tgtIntn = pairInfo.tgtIntn = tgtOutside;
        var intersectionPts = pairInfo.intersectionPts = {
          x1: srcOutside[0],
          x2: tgtOutside[0],
          y1: srcOutside[1],
          y2: tgtOutside[1]
        };
        var posPts = pairInfo.posPts = {
          x1: srcPos.x,
          x2: tgtPos.x,
          y1: srcPos.y,
          y2: tgtPos.y
        };
        var dy = tgtOutside[1] - srcOutside[1];
        var dx = tgtOutside[0] - srcOutside[0];
        var l = Math.sqrt(dx * dx + dy * dy);
        if (number$1(l) && l >= AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L) ; else {
          l = Math.sqrt(Math.max(dx * dx, AVOID_IMPOSSIBLE_BEZIER_CONSTANT) + Math.max(dy * dy, AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
        }
        var vector = pairInfo.vector = {
          x: dx,
          y: dy
        };
        var vectorNorm = pairInfo.vectorNorm = {
          x: vector.x / l,
          y: vector.y / l
        };
        var vectorNormInverse = {
          x: -vectorNorm.y,
          y: vectorNorm.x
        };

        // if node shapes overlap, then no ctrl pts to draw
        pairInfo.nodesOverlap = !number$1(l) || tgtShape.checkPoint(srcOutside[0], srcOutside[1], 0, tgtW, tgtH, tgtPos.x, tgtPos.y, tgtCornerRadius, tgtRs) || srcShape.checkPoint(tgtOutside[0], tgtOutside[1], 0, srcW, srcH, srcPos.x, srcPos.y, srcCornerRadius, srcRs);
        pairInfo.vectorNormInverse = vectorNormInverse;
        swappedpairInfo = {
          nodesOverlap: pairInfo.nodesOverlap,
          dirCounts: pairInfo.dirCounts,
          calculatedIntersection: true,
          hasBezier: pairInfo.hasBezier,
          hasUnbundled: pairInfo.hasUnbundled,
          eles: pairInfo.eles,
          srcPos: tgtPos,
          srcRs: tgtRs,
          tgtPos: srcPos,
          tgtRs: srcRs,
          srcW: tgtW,
          srcH: tgtH,
          tgtW: srcW,
          tgtH: srcH,
          srcIntn: tgtIntn,
          tgtIntn: srcIntn,
          srcShape: tgtShape,
          tgtShape: srcShape,
          posPts: {
            x1: posPts.x2,
            y1: posPts.y2,
            x2: posPts.x1,
            y2: posPts.y1
          },
          intersectionPts: {
            x1: intersectionPts.x2,
            y1: intersectionPts.y2,
            x2: intersectionPts.x1,
            y2: intersectionPts.y1
          },
          vector: {
            x: -vector.x,
            y: -vector.y
          },
          vectorNorm: {
            x: -vectorNorm.x,
            y: -vectorNorm.y
          },
          vectorNormInverse: {
            x: -vectorNormInverse.x,
            y: -vectorNormInverse.y
          }
        };
      }
      var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;
      rs.nodesOverlap = passedPairInfo.nodesOverlap;
      rs.srcIntn = passedPairInfo.srcIntn;
      rs.tgtIntn = passedPairInfo.tgtIntn;
      rs.isRound = _curveStyle.startsWith('round');
      if (hasCompounds && (src.isParent() || src.isChild() || tgt.isParent() || tgt.isChild()) && (src.parents().anySame(tgt) || tgt.parents().anySame(src) || src.same(tgt) && src.isParent())) {
        _this.findCompoundLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
      } else if (src === tgt) {
        _this.findLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
      } else if (_curveStyle.endsWith('segments')) {
        _this.findSegmentsPoints(_edge, passedPairInfo);
      } else if (_curveStyle.endsWith('taxi')) {
        _this.findTaxiPoints(_edge, passedPairInfo);
      } else if (_curveStyle === 'straight' || !_edgeIsUnbundled && pairInfo.eles.length % 2 === 1 && _i2 === Math.floor(pairInfo.eles.length / 2)) {
        _this.findStraightEdgePoints(_edge);
      } else {
        _this.findBezierPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled, edgeIsSwapped);
      }
      _this.findEndpoints(_edge);
      _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);
      _this.checkForInvalidEdgeWarning(_edge);
      _this.storeAllpts(_edge);
      _this.storeEdgeProjections(_edge);
      _this.calculateArrowAngles(_edge);
      _this.recalculateEdgeLabelProjections(_edge);
      _this.calculateLabelAngles(_edge);
    } // for pair edges
  };
  for (var p = 0; p < pairIds.length; p++) {
    _loop();
  } // for pair ids

  // haystacks avoid the expense of pairInfo stuff (intersections etc.)
  this.findHaystackPoints(haystackEdges);
};
function getPts(pts) {
  var retPts = [];
  if (pts == null) {
    return;
  }
  for (var i = 0; i < pts.length; i += 2) {
    var x = pts[i];
    var y = pts[i + 1];
    retPts.push({
      x: x,
      y: y
    });
  }
  return retPts;
}
BRp$c.getSegmentPoints = function (edge) {
  var rs = edge[0]._private.rscratch;
  this.recalculateRenderedStyle(edge);
  var type = rs.edgeType;
  if (type === 'segments') {
    return getPts(rs.segpts);
  }
};
BRp$c.getControlPoints = function (edge) {
  var rs = edge[0]._private.rscratch;
  this.recalculateRenderedStyle(edge);
  var type = rs.edgeType;
  if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {
    return getPts(rs.ctrlpts);
  }
};
BRp$c.getEdgeMidpoint = function (edge) {
  var rs = edge[0]._private.rscratch;
  this.recalculateRenderedStyle(edge);
  return {
    x: rs.midX,
    y: rs.midY
  };
};

var BRp$b = {};
BRp$b.manualEndptToPx = function (node, prop) {
  var r = this;
  var npos = node.position();
  var w = node.outerWidth();
  var h = node.outerHeight();
  var rs = node._private.rscratch;
  if (prop.value.length === 2) {
    var p = [prop.pfValue[0], prop.pfValue[1]];
    if (prop.units[0] === '%') {
      p[0] = p[0] * w;
    }
    if (prop.units[1] === '%') {
      p[1] = p[1] * h;
    }
    p[0] += npos.x;
    p[1] += npos.y;
    return p;
  } else {
    var angle = prop.pfValue[0];
    angle = -Math.PI / 2 + angle; // start at 12 o'clock

    var l = 2 * Math.max(w, h);
    var _p = [npos.x + Math.cos(angle) * l, npos.y + Math.sin(angle) * l];
    return r.nodeShapes[this.getNodeShape(node)].intersectLine(npos.x, npos.y, w, h, _p[0], _p[1], 0, node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue, rs);
  }
};
BRp$b.findEndpoints = function (edge) {
  var _ref, _tgtManEndpt$pfValue, _ref2, _srcManEndpt$pfValue;
  var r = this;
  var intersect;
  var source = edge.source()[0];
  var target = edge.target()[0];
  var srcPos = source.position();
  var tgtPos = target.position();
  var tgtArShape = edge.pstyle('target-arrow-shape').value;
  var srcArShape = edge.pstyle('source-arrow-shape').value;
  var tgtDist = edge.pstyle('target-distance-from-node').pfValue;
  var srcDist = edge.pstyle('source-distance-from-node').pfValue;
  var srcRs = source._private.rscratch;
  var tgtRs = target._private.rscratch;
  var curveStyle = edge.pstyle('curve-style').value;
  var rs = edge._private.rscratch;
  var et = rs.edgeType;
  var taxi = endsWith(curveStyle, 'taxi'); // Covers taxi and round-taxi
  var self = et === 'self' || et === 'compound';
  var bezier = et === 'bezier' || et === 'multibezier' || self;
  var multi = et !== 'bezier';
  var lines = et === 'straight' || et === 'segments';
  var segments = et === 'segments';
  var hasEndpts = bezier || multi || lines;
  var overrideEndpts = self || taxi;
  var srcManEndpt = edge.pstyle('source-endpoint');
  var srcManEndptVal = overrideEndpts ? 'outside-to-node' : srcManEndpt.value;
  var srcCornerRadius = source.pstyle('corner-radius').value === 'auto' ? 'auto' : source.pstyle('corner-radius').pfValue;
  var tgtManEndpt = edge.pstyle('target-endpoint');
  var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;
  var tgtCornerRadius = target.pstyle('corner-radius').value === 'auto' ? 'auto' : target.pstyle('corner-radius').pfValue;
  rs.srcManEndpt = srcManEndpt;
  rs.tgtManEndpt = tgtManEndpt;
  var p1; // last known point of edge on target side
  var p2; // last known point of edge on source side

  var p1_i; // point to intersect with target shape
  var p2_i; // point to intersect with source shape

  var tgtManEndptPt = (_ref = (tgtManEndpt === null || tgtManEndpt === undefined || (_tgtManEndpt$pfValue = tgtManEndpt.pfValue) === null || _tgtManEndpt$pfValue === undefined ? undefined : _tgtManEndpt$pfValue.length) === 2 ? tgtManEndpt.pfValue : null) !== null && _ref !== undefined ? _ref : [0, 0];
  var srcManEndptPt = (_ref2 = (srcManEndpt === null || srcManEndpt === undefined || (_srcManEndpt$pfValue = srcManEndpt.pfValue) === null || _srcManEndpt$pfValue === undefined ? undefined : _srcManEndpt$pfValue.length) === 2 ? srcManEndpt.pfValue : null) !== null && _ref2 !== undefined ? _ref2 : [0, 0];
  if (bezier) {
    var cpStart = [rs.ctrlpts[0], rs.ctrlpts[1]];
    var cpEnd = multi ? [rs.ctrlpts[rs.ctrlpts.length - 2], rs.ctrlpts[rs.ctrlpts.length - 1]] : cpStart;
    p1 = cpEnd;
    p2 = cpStart;
  } else if (lines) {
    var srcArrowFromPt = !segments ? [tgtPos.x + tgtManEndptPt[0], tgtPos.y + tgtManEndptPt[1]] : rs.segpts.slice(0, 2);
    var tgtArrowFromPt = !segments ? [srcPos.x + srcManEndptPt[0], srcPos.y + srcManEndptPt[1]] : rs.segpts.slice(rs.segpts.length - 2);
    p1 = tgtArrowFromPt;
    p2 = srcArrowFromPt;
  }
  if (tgtManEndptVal === 'inside-to-node') {
    intersect = [tgtPos.x, tgtPos.y];
  } else if (tgtManEndpt.units) {
    intersect = this.manualEndptToPx(target, tgtManEndpt);
  } else if (tgtManEndptVal === 'outside-to-line') {
    intersect = rs.tgtIntn; // use cached value from ctrlpt calc
  } else {
    if (tgtManEndptVal === 'outside-to-node' || tgtManEndptVal === 'outside-to-node-or-label') {
      p1_i = p1;
    } else if (tgtManEndptVal === 'outside-to-line' || tgtManEndptVal === 'outside-to-line-or-label') {
      p1_i = [srcPos.x, srcPos.y];
    }
    intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0, tgtCornerRadius, tgtRs);
    if (tgtManEndptVal === 'outside-to-node-or-label' || tgtManEndptVal === 'outside-to-line-or-label') {
      var trs = target._private.rscratch;
      var lw = trs.labelWidth;
      var lh = trs.labelHeight;
      var lx = trs.labelX;
      var ly = trs.labelY;
      var lw2 = lw / 2;
      var lh2 = lh / 2;
      var va = target.pstyle('text-valign').value;
      if (va === 'top') {
        ly -= lh2;
      } else if (va === 'bottom') {
        ly += lh2;
      }
      var ha = target.pstyle('text-halign').value;
      if (ha === 'left') {
        lx -= lw2;
      } else if (ha === 'right') {
        lx += lw2;
      }
      var labelIntersect = polygonIntersectLine(p1_i[0], p1_i[1], [lx - lw2, ly - lh2, lx + lw2, ly - lh2, lx + lw2, ly + lh2, lx - lw2, ly + lh2], tgtPos.x, tgtPos.y);
      if (labelIntersect.length > 0) {
        var refPt = srcPos;
        var intSqdist = sqdist(refPt, array2point(intersect));
        var labIntSqdist = sqdist(refPt, array2point(labelIntersect));
        var minSqDist = intSqdist;
        if (labIntSqdist < intSqdist) {
          intersect = labelIntersect;
          minSqDist = labIntSqdist;
        }
        if (labelIntersect.length > 2) {
          var labInt2SqDist = sqdist(refPt, {
            x: labelIntersect[2],
            y: labelIntersect[3]
          });
          if (labInt2SqDist < minSqDist) {
            intersect = [labelIntersect[2], labelIntersect[3]];
          }
        }
      }
    }
  }
  var arrowEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].spacing(edge) + tgtDist);
  var edgeEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].gap(edge) + tgtDist);
  rs.endX = edgeEnd[0];
  rs.endY = edgeEnd[1];
  rs.arrowEndX = arrowEnd[0];
  rs.arrowEndY = arrowEnd[1];
  if (srcManEndptVal === 'inside-to-node') {
    intersect = [srcPos.x, srcPos.y];
  } else if (srcManEndpt.units) {
    intersect = this.manualEndptToPx(source, srcManEndpt);
  } else if (srcManEndptVal === 'outside-to-line') {
    intersect = rs.srcIntn; // use cached value from ctrlpt calc
  } else {
    if (srcManEndptVal === 'outside-to-node' || srcManEndptVal === 'outside-to-node-or-label') {
      p2_i = p2;
    } else if (srcManEndptVal === 'outside-to-line' || srcManEndptVal === 'outside-to-line-or-label') {
      p2_i = [tgtPos.x, tgtPos.y];
    }
    intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0, srcCornerRadius, srcRs);
    if (srcManEndptVal === 'outside-to-node-or-label' || srcManEndptVal === 'outside-to-line-or-label') {
      var srs = source._private.rscratch;
      var _lw = srs.labelWidth;
      var _lh = srs.labelHeight;
      var _lx = srs.labelX;
      var _ly = srs.labelY;
      var _lw2 = _lw / 2;
      var _lh2 = _lh / 2;
      var _va = source.pstyle('text-valign').value;
      if (_va === 'top') {
        _ly -= _lh2;
      } else if (_va === 'bottom') {
        _ly += _lh2;
      }
      var _ha = source.pstyle('text-halign').value;
      if (_ha === 'left') {
        _lx -= _lw2;
      } else if (_ha === 'right') {
        _lx += _lw2;
      }
      var _labelIntersect = polygonIntersectLine(p2_i[0], p2_i[1], [_lx - _lw2, _ly - _lh2, _lx + _lw2, _ly - _lh2, _lx + _lw2, _ly + _lh2, _lx - _lw2, _ly + _lh2], srcPos.x, srcPos.y);
      if (_labelIntersect.length > 0) {
        var _refPt = tgtPos;
        var _intSqdist = sqdist(_refPt, array2point(intersect));
        var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));
        var _minSqDist = _intSqdist;
        if (_labIntSqdist < _intSqdist) {
          intersect = [_labelIntersect[0], _labelIntersect[1]];
          _minSqDist = _labIntSqdist;
        }
        if (_labelIntersect.length > 2) {
          var _labInt2SqDist = sqdist(_refPt, {
            x: _labelIntersect[2],
            y: _labelIntersect[3]
          });
          if (_labInt2SqDist < _minSqDist) {
            intersect = [_labelIntersect[2], _labelIntersect[3]];
          }
        }
      }
    }
  }
  var arrowStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].spacing(edge) + srcDist);
  var edgeStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].gap(edge) + srcDist);
  rs.startX = edgeStart[0];
  rs.startY = edgeStart[1];
  rs.arrowStartX = arrowStart[0];
  rs.arrowStartY = arrowStart[1];
  if (hasEndpts) {
    if (!number$1(rs.startX) || !number$1(rs.startY) || !number$1(rs.endX) || !number$1(rs.endY)) {
      rs.badLine = true;
    } else {
      rs.badLine = false;
    }
  }
};
BRp$b.getSourceEndpoint = function (edge) {
  var rs = edge[0]._private.rscratch;
  this.recalculateRenderedStyle(edge);
  switch (rs.edgeType) {
    case 'haystack':
      return {
        x: rs.haystackPts[0],
        y: rs.haystackPts[1]
      };
    default:
      return {
        x: rs.arrowStartX,
        y: rs.arrowStartY
      };
  }
};
BRp$b.getTargetEndpoint = function (edge) {
  var rs = edge[0]._private.rscratch;
  this.recalculateRenderedStyle(edge);
  switch (rs.edgeType) {
    case 'haystack':
      return {
        x: rs.haystackPts[2],
        y: rs.haystackPts[3]
      };
    default:
      return {
        x: rs.arrowEndX,
        y: rs.arrowEndY
      };
  }
};

var BRp$a = {};
function pushBezierPts(r, edge, pts) {
  var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {
    return qbezierAt(p1, p2, p3, t);
  };
  var _p = edge._private;
  var bpts = _p.rstyle.bezierPts;
  for (var i = 0; i < r.bezierProjPcts.length; i++) {
    var p = r.bezierProjPcts[i];
    bpts.push({
      x: qbezierAt$1(pts[0], pts[2], pts[4], p),
      y: qbezierAt$1(pts[1], pts[3], pts[5], p)
    });
  }
}
BRp$a.storeEdgeProjections = function (edge) {
  var _p = edge._private;
  var rs = _p.rscratch;
  var et = rs.edgeType;

  // clear the cached points state
  _p.rstyle.bezierPts = null;
  _p.rstyle.linePts = null;
  _p.rstyle.haystackPts = null;
  if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {
    _p.rstyle.bezierPts = [];
    for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
      pushBezierPts(this, edge, rs.allpts.slice(i, i + 6));
    }
  } else if (et === 'segments') {
    var lpts = _p.rstyle.linePts = [];
    for (var i = 0; i + 1 < rs.allpts.length; i += 2) {
      lpts.push({
        x: rs.allpts[i],
        y: rs.allpts[i + 1]
      });
    }
  } else if (et === 'haystack') {
    var hpts = rs.haystackPts;
    _p.rstyle.haystackPts = [{
      x: hpts[0],
      y: hpts[1]
    }, {
      x: hpts[2],
      y: hpts[3]
    }];
  }
  _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
};
BRp$a.recalculateEdgeProjections = function (edges) {
  this.findEdgeControlPoints(edges);
};

var BRp$9 = {};
BRp$9.recalculateNodeLabelProjection = function (node) {
  var content = node.pstyle('label').strValue;
  if (emptyString(content)) {
    return;
  }
  var textX, textY;
  var _p = node._private;
  var nodeWidth = node.width();
  var nodeHeight = node.height();
  var padding = node.padding();
  var nodePos = node.position();
  var textHalign = node.pstyle('text-halign').strValue;
  var textValign = node.pstyle('text-valign').strValue;
  var rs = _p.rscratch;
  var rstyle = _p.rstyle;
  switch (textHalign) {
    case 'left':
      textX = nodePos.x - nodeWidth / 2 - padding;
      break;
    case 'right':
      textX = nodePos.x + nodeWidth / 2 + padding;
      break;
    default:
      // e.g. center
      textX = nodePos.x;
  }
  switch (textValign) {
    case 'top':
      textY = nodePos.y - nodeHeight / 2 - padding;
      break;
    case 'bottom':
      textY = nodePos.y + nodeHeight / 2 + padding;
      break;
    default:
      // e.g. middle
      textY = nodePos.y;
  }
  rs.labelX = textX;
  rs.labelY = textY;
  rstyle.labelX = textX;
  rstyle.labelY = textY;
  this.calculateLabelAngles(node);
  this.applyLabelDimensions(node);
};
var lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {
  var angle = Math.atan(dy / dx);
  if (dx === 0 && angle < 0) {
    angle = angle * -1;
  }
  return angle;
};
var lineAngle = function lineAngle(p0, p1) {
  var dx = p1.x - p0.x;
  var dy = p1.y - p0.y;
  return lineAngleFromDelta(dx, dy);
};
var bezierAngle = function bezierAngle(p0, p1, p2, t) {
  var t0 = bound(0, t - 0.001, 1);
  var t1 = bound(0, t + 0.001, 1);
  var lp0 = qbezierPtAt(p0, p1, p2, t0);
  var lp1 = qbezierPtAt(p0, p1, p2, t1);
  return lineAngle(lp0, lp1);
};
BRp$9.recalculateEdgeLabelProjections = function (edge) {
  var p;
  var _p = edge._private;
  var rs = _p.rscratch;
  var r = this;
  var content = {
    mid: edge.pstyle('label').strValue,
    source: edge.pstyle('source-label').strValue,
    target: edge.pstyle('target-label').strValue
  };
  if (content.mid || content.source || content.target) ; else {
    return; // no labels => no calcs
  }

  // add center point to style so bounding box calculations can use it
  //
  p = {
    x: rs.midX,
    y: rs.midY
  };
  var setRs = function setRs(propName, prefix, value) {
    setPrefixedProperty(_p.rscratch, propName, prefix, value);
    setPrefixedProperty(_p.rstyle, propName, prefix, value);
  };
  setRs('labelX', null, p.x);
  setRs('labelY', null, p.y);
  var midAngle = lineAngleFromDelta(rs.midDispX, rs.midDispY);
  setRs('labelAutoAngle', null, midAngle);
  var _createControlPointInfo = function createControlPointInfo() {
    if (_createControlPointInfo.cache) {
      return _createControlPointInfo.cache;
    } // use cache so only 1x per edge

    var ctrlpts = [];

    // store each ctrlpt info init
    for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
      var p0 = {
        x: rs.allpts[i],
        y: rs.allpts[i + 1]
      };
      var p1 = {
        x: rs.allpts[i + 2],
        y: rs.allpts[i + 3]
      }; // ctrlpt
      var p2 = {
        x: rs.allpts[i + 4],
        y: rs.allpts[i + 5]
      };
      ctrlpts.push({
        p0: p0,
        p1: p1,
        p2: p2,
        startDist: 0,
        length: 0,
        segments: []
      });
    }
    var bpts = _p.rstyle.bezierPts;
    var nProjs = r.bezierProjPcts.length;
    function addSegment(cp, p0, p1, t0, t1) {
      var length = dist(p0, p1);
      var prevSegment = cp.segments[cp.segments.length - 1];
      var segment = {
        p0: p0,
        p1: p1,
        t0: t0,
        t1: t1,
        startDist: prevSegment ? prevSegment.startDist + prevSegment.length : 0,
        length: length
      };
      cp.segments.push(segment);
      cp.length += length;
    }

    // update each ctrlpt with segment info
    for (var _i = 0; _i < ctrlpts.length; _i++) {
      var cp = ctrlpts[_i];
      var prevCp = ctrlpts[_i - 1];
      if (prevCp) {
        cp.startDist = prevCp.startDist + prevCp.length;
      }
      addSegment(cp, cp.p0, bpts[_i * nProjs], 0, r.bezierProjPcts[0]); // first

      for (var j = 0; j < nProjs - 1; j++) {
        addSegment(cp, bpts[_i * nProjs + j], bpts[_i * nProjs + j + 1], r.bezierProjPcts[j], r.bezierProjPcts[j + 1]);
      }
      addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last
    }
    return _createControlPointInfo.cache = ctrlpts;
  };
  var calculateEndProjection = function calculateEndProjection(prefix) {
    var angle;
    var isSrc = prefix === 'source';
    if (!content[prefix]) {
      return;
    }
    var offset = edge.pstyle(prefix + '-text-offset').pfValue;
    switch (rs.edgeType) {
      case 'self':
      case 'compound':
      case 'bezier':
      case 'multibezier':
        {
          var cps = _createControlPointInfo();
          var selected;
          var startDist = 0;
          var totalDist = 0;

          // find the segment we're on
          for (var i = 0; i < cps.length; i++) {
            var _cp = cps[isSrc ? i : cps.length - 1 - i];
            for (var j = 0; j < _cp.segments.length; j++) {
              var _seg = _cp.segments[isSrc ? j : _cp.segments.length - 1 - j];
              var lastSeg = i === cps.length - 1 && j === _cp.segments.length - 1;
              startDist = totalDist;
              totalDist += _seg.length;
              if (totalDist >= offset || lastSeg) {
                selected = {
                  cp: _cp,
                  segment: _seg
                };
                break;
              }
            }
            if (selected) {
              break;
            }
          }
          var cp = selected.cp;
          var seg = selected.segment;
          var tSegment = (offset - startDist) / seg.length;
          var segDt = seg.t1 - seg.t0;
          var t = isSrc ? seg.t0 + segDt * tSegment : seg.t1 - segDt * tSegment;
          t = bound(0, t, 1);
          p = qbezierPtAt(cp.p0, cp.p1, cp.p2, t);
          angle = bezierAngle(cp.p0, cp.p1, cp.p2, t);
          break;
        }
      case 'straight':
      case 'segments':
      case 'haystack':
        {
          var d = 0,
            di,
            d0;
          var p0, p1;
          var l = rs.allpts.length;
          for (var _i2 = 0; _i2 + 3 < l; _i2 += 2) {
            if (isSrc) {
              p0 = {
                x: rs.allpts[_i2],
                y: rs.allpts[_i2 + 1]
              };
              p1 = {
                x: rs.allpts[_i2 + 2],
                y: rs.allpts[_i2 + 3]
              };
            } else {
              p0 = {
                x: rs.allpts[l - 2 - _i2],
                y: rs.allpts[l - 1 - _i2]
              };
              p1 = {
                x: rs.allpts[l - 4 - _i2],
                y: rs.allpts[l - 3 - _i2]
              };
            }
            di = dist(p0, p1);
            d0 = d;
            d += di;
            if (d >= offset) {
              break;
            }
          }
          var pD = offset - d0;
          var _t = pD / di;
          _t = bound(0, _t, 1);
          p = lineAt(p0, p1, _t);
          angle = lineAngle(p0, p1);
          break;
        }
    }
    setRs('labelX', prefix, p.x);
    setRs('labelY', prefix, p.y);
    setRs('labelAutoAngle', prefix, angle);
  };
  calculateEndProjection('source');
  calculateEndProjection('target');
  this.applyLabelDimensions(edge);
};
BRp$9.applyLabelDimensions = function (ele) {
  this.applyPrefixedLabelDimensions(ele);
  if (ele.isEdge()) {
    this.applyPrefixedLabelDimensions(ele, 'source');
    this.applyPrefixedLabelDimensions(ele, 'target');
  }
};
BRp$9.applyPrefixedLabelDimensions = function (ele, prefix) {
  var _p = ele._private;
  var text = this.getLabelText(ele, prefix);
  var cacheKey = hashString(text, ele._private.labelDimsKey);

  // save recalc if the label is the same as before
  if (getPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix) === cacheKey) {
    return; // then the label dimensions + text are the same
  }

  // save the key
  setPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix, cacheKey);
  var labelDims = this.calculateLabelDimensions(ele, text);
  var lineHeight = ele.pstyle('line-height').pfValue;
  var textWrap = ele.pstyle('text-wrap').strValue;
  var lines = getPrefixedProperty(_p.rscratch, 'labelWrapCachedLines', prefix) || [];
  var numLines = textWrap !== 'wrap' ? 1 : Math.max(lines.length, 1);
  var normPerLineHeight = labelDims.height / numLines;
  var labelLineHeight = normPerLineHeight * lineHeight;
  var width = labelDims.width;
  var height = labelDims.height + (numLines - 1) * (lineHeight - 1) * normPerLineHeight;
  setPrefixedProperty(_p.rstyle, 'labelWidth', prefix, width);
  setPrefixedProperty(_p.rscratch, 'labelWidth', prefix, width);
  setPrefixedProperty(_p.rstyle, 'labelHeight', prefix, height);
  setPrefixedProperty(_p.rscratch, 'labelHeight', prefix, height);
  setPrefixedProperty(_p.rscratch, 'labelLineHeight', prefix, labelLineHeight);
};
BRp$9.getLabelText = function (ele, prefix) {
  var _p = ele._private;
  var pfd = prefix ? prefix + '-' : '';
  var text = ele.pstyle(pfd + 'label').strValue;
  var textTransform = ele.pstyle('text-transform').value;
  var rscratch = function rscratch(propName, value) {
    if (value) {
      setPrefixedProperty(_p.rscratch, propName, prefix, value);
      return value;
    } else {
      return getPrefixedProperty(_p.rscratch, propName, prefix);
    }
  };

  // for empty text, skip all processing
  if (!text) {
    return '';
  }
  if (textTransform == 'none') ; else if (textTransform == 'uppercase') {
    text = text.toUpperCase();
  } else if (textTransform == 'lowercase') {
    text = text.toLowerCase();
  }
  var wrapStyle = ele.pstyle('text-wrap').value;
  if (wrapStyle === 'wrap') {
    var labelKey = rscratch('labelKey');

    // save recalc if the label is the same as before
    if (labelKey != null && rscratch('labelWrapKey') === labelKey) {
      return rscratch('labelWrapCachedText');
    }
    var zwsp = "\u200B";
    var lines = text.split('\n');
    var maxW = ele.pstyle('text-max-width').pfValue;
    var overflow = ele.pstyle('text-overflow-wrap').value;
    var overflowAny = overflow === 'anywhere';
    var wrappedLines = [];
    var separatorRegex = /[\s\u200b]+|$/g; // Include end of string to add last word

    for (var l = 0; l < lines.length; l++) {
      var line = lines[l];
      var lineDims = this.calculateLabelDimensions(ele, line);
      var lineW = lineDims.width;
      if (overflowAny) {
        var processedLine = line.split('').join(zwsp);
        line = processedLine;
      }
      if (lineW > maxW) {
        // line is too long
        var separatorMatches = line.matchAll(separatorRegex);
        var subline = '';
        var previousIndex = 0;
        // Add fake match
        var _iterator = _createForOfIteratorHelper(separatorMatches),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var separatorMatch = _step.value;
            var wordSeparator = separatorMatch[0];
            var word = line.substring(previousIndex, separatorMatch.index);
            previousIndex = separatorMatch.index + wordSeparator.length;
            var testLine = subline.length === 0 ? word : subline + word + wordSeparator;
            var testDims = this.calculateLabelDimensions(ele, testLine);
            var testW = testDims.width;
            if (testW <= maxW) {
              // word fits on current line
              subline += word + wordSeparator;
            } else {
              // word starts new line
              if (subline) {
                wrappedLines.push(subline);
              }
              subline = word + wordSeparator;
            }
          }

          // if there's remaining text, put it in a wrapped line
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        if (!subline.match(/^[\s\u200b]+$/)) {
          wrappedLines.push(subline);
        }
      } else {
        // line is already short enough
        wrappedLines.push(line);
      }
    } // for

    rscratch('labelWrapCachedLines', wrappedLines);
    text = rscratch('labelWrapCachedText', wrappedLines.join('\n'));
    rscratch('labelWrapKey', labelKey);
  } else if (wrapStyle === 'ellipsis') {
    var _maxW = ele.pstyle('text-max-width').pfValue;
    var ellipsized = '';
    var ellipsis = "\u2026";
    var incLastCh = false;
    if (this.calculateLabelDimensions(ele, text).width < _maxW) {
      // the label already fits
      return text;
    }
    for (var i = 0; i < text.length; i++) {
      var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;
      if (widthWithNextCh > _maxW) {
        break;
      }
      ellipsized += text[i];
      if (i === text.length - 1) {
        incLastCh = true;
      }
    }
    if (!incLastCh) {
      ellipsized += ellipsis;
    }
    return ellipsized;
  } // if ellipsize

  return text;
};
BRp$9.getLabelJustification = function (ele) {
  var justification = ele.pstyle('text-justification').strValue;
  var textHalign = ele.pstyle('text-halign').strValue;
  if (justification === 'auto') {
    if (ele.isNode()) {
      switch (textHalign) {
        case 'left':
          return 'right';
        case 'right':
          return 'left';
        default:
          return 'center';
      }
    } else {
      return 'center';
    }
  } else {
    return justification;
  }
};
BRp$9.calculateLabelDimensions = function (ele, text) {
  var r = this;
  var containerWindow = r.cy.window();
  var document = containerWindow.document;
  var padding = 0; // add padding around text dims, as the measurement isn't that accurate
  var fStyle = ele.pstyle('font-style').strValue;
  var size = ele.pstyle('font-size').pfValue;
  var family = ele.pstyle('font-family').strValue;
  var weight = ele.pstyle('font-weight').strValue;
  var canvas = this.labelCalcCanvas;
  var c2d = this.labelCalcCanvasContext;
  if (!canvas) {
    canvas = this.labelCalcCanvas = document.createElement('canvas');
    c2d = this.labelCalcCanvasContext = canvas.getContext('2d');
    var ds = canvas.style;
    ds.position = 'absolute';
    ds.left = '-9999px';
    ds.top = '-9999px';
    ds.zIndex = '-1';
    ds.visibility = 'hidden';
    ds.pointerEvents = 'none';
  }
  c2d.font = "".concat(fStyle, " ").concat(weight, " ").concat(size, "px ").concat(family);
  var width = 0;
  var height = 0;
  var lines = text.split('\n');
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var metrics = c2d.measureText(line);
    var w = Math.ceil(metrics.width);
    var h = size;
    width = Math.max(w, width);
    height += h;
  }
  width += padding;
  height += padding;
  return {
    width: width,
    height: height
  };
};
BRp$9.calculateLabelAngle = function (ele, prefix) {
  var _p = ele._private;
  var rs = _p.rscratch;
  var isEdge = ele.isEdge();
  var prefixDash = prefix ? prefix + '-' : '';
  var rot = ele.pstyle(prefixDash + 'text-rotation');
  var rotStr = rot.strValue;
  if (rotStr === 'none') {
    return 0;
  } else if (isEdge && rotStr === 'autorotate') {
    return rs.labelAutoAngle;
  } else if (rotStr === 'autorotate') {
    return 0;
  } else {
    return rot.pfValue;
  }
};
BRp$9.calculateLabelAngles = function (ele) {
  var r = this;
  var isEdge = ele.isEdge();
  var _p = ele._private;
  var rs = _p.rscratch;
  rs.labelAngle = r.calculateLabelAngle(ele);
  if (isEdge) {
    rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');
    rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');
  }
};

var BRp$8 = {};
var TOO_SMALL_CUT_RECT = 28;
var warnedCutRect = false;
BRp$8.getNodeShape = function (node) {
  var r = this;
  var shape = node.pstyle('shape').value;
  if (shape === 'cutrectangle' && (node.width() < TOO_SMALL_CUT_RECT || node.height() < TOO_SMALL_CUT_RECT)) {
    if (!warnedCutRect) {
      warn('The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead');
      warnedCutRect = true;
    }
    return 'rectangle';
  }
  if (node.isParent()) {
    if (shape === 'rectangle' || shape === 'roundrectangle' || shape === 'round-rectangle' || shape === 'cutrectangle' || shape === 'cut-rectangle' || shape === 'barrel') {
      return shape;
    } else {
      return 'rectangle';
    }
  }
  if (shape === 'polygon') {
    var points = node.pstyle('shape-polygon-points').value;
    return r.nodeShapes.makePolygon(points).name;
  }
  return shape;
};

var BRp$7 = {};
BRp$7.registerCalculationListeners = function () {
  var cy = this.cy;
  var elesToUpdate = cy.collection();
  var r = this;
  var enqueue = function enqueue(eles) {
    var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    elesToUpdate.merge(eles);
    if (dirtyStyleCaches) {
      for (var i = 0; i < eles.length; i++) {
        var ele = eles[i];
        var _p = ele._private;
        var rstyle = _p.rstyle;
        rstyle.clean = false;
        rstyle.cleanConnected = false;
      }
    }
  };
  r.binder(cy).on('bounds.* dirty.*', function onDirtyBounds(e) {
    var ele = e.target;
    enqueue(ele);
  }).on('style.* background.*', function onDirtyStyle(e) {
    var ele = e.target;
    enqueue(ele, false);
  });
  var updateEleCalcs = function updateEleCalcs(willDraw) {
    if (willDraw) {
      var fns = r.onUpdateEleCalcsFns;

      // because we need to have up-to-date style (e.g. stylesheet mappers)
      // before calculating rendered style (and pstyle might not be called yet)
      elesToUpdate.cleanStyle();
      for (var i = 0; i < elesToUpdate.length; i++) {
        var ele = elesToUpdate[i];
        var rstyle = ele._private.rstyle;
        if (ele.isNode() && !rstyle.cleanConnected) {
          enqueue(ele.connectedEdges());
          rstyle.cleanConnected = true;
        }
      }
      if (fns) {
        for (var _i = 0; _i < fns.length; _i++) {
          var fn = fns[_i];
          fn(willDraw, elesToUpdate);
        }
      }
      r.recalculateRenderedStyle(elesToUpdate);
      elesToUpdate = cy.collection();
    }
  };
  r.flushRenderedStyleQueue = function () {
    updateEleCalcs(true);
  };
  r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);
};
BRp$7.onUpdateEleCalcs = function (fn) {
  var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];
  fns.push(fn);
};
BRp$7.recalculateRenderedStyle = function (eles, useCache) {
  var isCleanConnected = function isCleanConnected(ele) {
    return ele._private.rstyle.cleanConnected;
  };
  if (eles.length === 0) {
    return;
  }
  var edges = [];
  var nodes = [];

  // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()
  if (this.destroyed) {
    return;
  }

  // use cache by default for perf
  if (useCache === undefined) {
    useCache = true;
  }
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    var _p = ele._private;
    var rstyle = _p.rstyle;

    // an edge may be implicitly dirty b/c of one of its connected nodes
    // (and a request for recalc may come in between frames)
    if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {
      rstyle.clean = false;
    }
    if (ele.isEdge() && ele.isBundledBezier()) {
      if (ele.parallelEdges().some(function (ele) {
        return !ele._private.rstyle.clean && ele.isBundledBezier();
      })) {
        rstyle.clean = false;
      }
    }

    // only update if dirty and in graph
    if (useCache && rstyle.clean || ele.removed()) {
      continue;
    }

    // only update if not display: none
    if (ele.pstyle('display').value === 'none') {
      continue;
    }
    if (_p.group === 'nodes') {
      nodes.push(ele);
    } else {
      // edges
      edges.push(ele);
    }
    rstyle.clean = true;
  }

  // update node data from projections
  for (var _i2 = 0; _i2 < nodes.length; _i2++) {
    var _ele = nodes[_i2];
    var _p2 = _ele._private;
    var _rstyle = _p2.rstyle;
    var pos = _ele.position();
    this.recalculateNodeLabelProjection(_ele);
    _rstyle.nodeX = pos.x;
    _rstyle.nodeY = pos.y;
    _rstyle.nodeW = _ele.pstyle('width').pfValue;
    _rstyle.nodeH = _ele.pstyle('height').pfValue;
  }
  this.recalculateEdgeProjections(edges);

  // update edge data from projections
  for (var _i3 = 0; _i3 < edges.length; _i3++) {
    var _ele2 = edges[_i3];
    var _p3 = _ele2._private;
    var _rstyle2 = _p3.rstyle;
    var rs = _p3.rscratch;

    // update rstyle positions
    _rstyle2.srcX = rs.arrowStartX;
    _rstyle2.srcY = rs.arrowStartY;
    _rstyle2.tgtX = rs.arrowEndX;
    _rstyle2.tgtY = rs.arrowEndY;
    _rstyle2.midX = rs.midX;
    _rstyle2.midY = rs.midY;
    _rstyle2.labelAngle = rs.labelAngle;
    _rstyle2.sourceLabelAngle = rs.sourceLabelAngle;
    _rstyle2.targetLabelAngle = rs.targetLabelAngle;
  }
};

var BRp$6 = {};
BRp$6.updateCachedGrabbedEles = function () {
  var eles = this.cachedZSortedEles;
  if (!eles) {
    // just let this be recalculated on the next z sort tick
    return;
  }
  eles.drag = [];
  eles.nondrag = [];
  var grabTargets = [];
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    var rs = ele._private.rscratch;
    if (ele.grabbed() && !ele.isParent()) {
      grabTargets.push(ele);
    } else if (rs.inDragLayer) {
      eles.drag.push(ele);
    } else {
      eles.nondrag.push(ele);
    }
  }

  // put the grab target nodes last so it's on top of its neighbourhood
  for (var i = 0; i < grabTargets.length; i++) {
    var ele = grabTargets[i];
    eles.drag.push(ele);
  }
};
BRp$6.invalidateCachedZSortedEles = function () {
  this.cachedZSortedEles = null;
};
BRp$6.getCachedZSortedEles = function (forceRecalc) {
  if (forceRecalc || !this.cachedZSortedEles) {
    var eles = this.cy.mutableElements().toArray();
    eles.sort(zIndexSort);
    eles.interactive = eles.filter(function (ele) {
      return ele.interactive();
    });
    this.cachedZSortedEles = eles;
    this.updateCachedGrabbedEles();
  } else {
    eles = this.cachedZSortedEles;
  }
  return eles;
};

var BRp$5 = {};
[BRp$e, BRp$d, BRp$c, BRp$b, BRp$a, BRp$9, BRp$8, BRp$7, BRp$6].forEach(function (props) {
  extend(BRp$5, props);
});

var BRp$4 = {};
BRp$4.getCachedImage = function (url, crossOrigin, onLoad) {
  var r = this;
  var imageCache = r.imageCache = r.imageCache || {};
  var cache = imageCache[url];
  if (cache) {
    if (!cache.image.complete) {
      cache.image.addEventListener('load', onLoad);
    }
    return cache.image;
  } else {
    cache = imageCache[url] = imageCache[url] || {};
    var image = cache.image = new Image(); // eslint-disable-line no-undef

    image.addEventListener('load', onLoad);
    image.addEventListener('error', function () {
      image.error = true;
    });

    // #1582 safari doesn't load data uris with crossOrigin properly
    // https://bugs.webkit.org/show_bug.cgi?id=123978
    var dataUriPrefix = 'data:';
    var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;
    if (!isDataUri) {
      // if crossorigin is 'null'(stringified), then manually set it to null 
      crossOrigin = crossOrigin === 'null' ? null : crossOrigin;
      image.crossOrigin = crossOrigin; // prevent tainted canvas
    }
    image.src = url;
    return image;
  }
};

var BRp$3 = {};

/* global document, ResizeObserver, MutationObserver */

BRp$3.registerBinding = function (target, event, handler, useCapture) {
  // eslint-disable-line no-unused-vars
  var args = Array.prototype.slice.apply(arguments, [1]); // copy

  if (Array.isArray(target)) {
    var res = [];
    for (var i = 0; i < target.length; i++) {
      var t = target[i];
      if (t !== undefined) {
        var b = this.binder(t);
        res.push(b.on.apply(b, args));
      }
    }
    return res;
  }
  var b = this.binder(target);
  return b.on.apply(b, args);
};
BRp$3.binder = function (tgt) {
  var r = this;
  var containerWindow = r.cy.window();
  var tgtIsDom = tgt === containerWindow || tgt === containerWindow.document || tgt === containerWindow.document.body || domElement(tgt);
  if (r.supportsPassiveEvents == null) {
    // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
    var supportsPassive = false;
    try {
      var opts = Object.defineProperty({}, 'passive', {
        get: function get() {
          supportsPassive = true;
          return true;
        }
      });
      containerWindow.addEventListener('test', null, opts);
    } catch (err) {
      // not supported
    }
    r.supportsPassiveEvents = supportsPassive;
  }
  var on = function on(event, handler, useCapture) {
    var args = Array.prototype.slice.call(arguments);
    if (tgtIsDom && r.supportsPassiveEvents) {
      // replace useCapture w/ opts obj
      args[2] = {
        capture: useCapture != null ? useCapture : false,
        passive: false,
        once: false
      };
    }
    r.bindings.push({
      target: tgt,
      args: args
    });
    (tgt.addEventListener || tgt.on).apply(tgt, args);
    return this;
  };
  return {
    on: on,
    addEventListener: on,
    addListener: on,
    bind: on
  };
};
BRp$3.nodeIsDraggable = function (node) {
  return node && node.isNode() && !node.locked() && node.grabbable();
};
BRp$3.nodeIsGrabbable = function (node) {
  return this.nodeIsDraggable(node) && node.interactive();
};
BRp$3.load = function () {
  var r = this;
  var containerWindow = r.cy.window();
  var isSelected = function isSelected(ele) {
    return ele.selected();
  };
  var getShadowRoot = function getShadowRoot(element) {
    var rootNode = element.getRootNode();
    // Check if the root node is a shadow root
    if (rootNode && rootNode.nodeType === 11 && rootNode.host !== undefined) {
      return rootNode;
    }
  };
  var triggerEvents = function triggerEvents(target, names, e, position) {
    if (target == null) {
      target = r.cy;
    }
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      target.emit({
        originalEvent: e,
        type: name,
        position: position
      });
    }
  };
  var isMultSelKeyDown = function isMultSelKeyDown(e) {
    return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey
  };
  var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {
    var allowPassthrough = true;
    if (r.cy.hasCompoundNodes() && down && down.pannable()) {
      // a grabbable compound node below the ele => no passthrough panning
      for (var i = 0; downs && i < downs.length; i++) {
        var down = downs[i];

        //if any parent node in event hierarchy isn't pannable, reject passthrough
        if (down.isNode() && down.isParent() && !down.pannable()) {
          allowPassthrough = false;
          break;
        }
      }
    } else {
      allowPassthrough = true;
    }
    return allowPassthrough;
  };
  var setGrabbed = function setGrabbed(ele) {
    ele[0]._private.grabbed = true;
  };
  var setFreed = function setFreed(ele) {
    ele[0]._private.grabbed = false;
  };
  var setInDragLayer = function setInDragLayer(ele) {
    ele[0]._private.rscratch.inDragLayer = true;
  };
  var setOutDragLayer = function setOutDragLayer(ele) {
    ele[0]._private.rscratch.inDragLayer = false;
  };
  var setGrabTarget = function setGrabTarget(ele) {
    ele[0]._private.rscratch.isGrabTarget = true;
  };
  var removeGrabTarget = function removeGrabTarget(ele) {
    ele[0]._private.rscratch.isGrabTarget = false;
  };
  var addToDragList = function addToDragList(ele, opts) {
    var list = opts.addToList;
    var listHasEle = list.has(ele);
    if (!listHasEle && ele.grabbable() && !ele.locked()) {
      list.merge(ele);
      setGrabbed(ele);
    }
  };

  // helper function to determine which child nodes and inner edges
  // of a compound node to be dragged as well as the grabbed and selected nodes
  var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {
    if (!node.cy().hasCompoundNodes()) {
      return;
    }
    if (opts.inDragLayer == null && opts.addToList == null) {
      return;
    } // nothing to do

    var innerNodes = node.descendants();
    if (opts.inDragLayer) {
      innerNodes.forEach(setInDragLayer);
      innerNodes.connectedEdges().forEach(setInDragLayer);
    }
    if (opts.addToList) {
      addToDragList(innerNodes, opts);
    }
  };

  // adds the given nodes and its neighbourhood to the drag layer
  var addNodesToDrag = function addNodesToDrag(nodes, opts) {
    opts = opts || {};
    var hasCompoundNodes = nodes.cy().hasCompoundNodes();
    if (opts.inDragLayer) {
      nodes.forEach(setInDragLayer);
      nodes.neighborhood().stdFilter(function (ele) {
        return !hasCompoundNodes || ele.isEdge();
      }).forEach(setInDragLayer);
    }
    if (opts.addToList) {
      nodes.forEach(function (ele) {
        addToDragList(ele, opts);
      });
    }
    addDescendantsToDrag(nodes, opts); // always add to drag

    // also add nodes and edges related to the topmost ancestor
    updateAncestorsInDragLayer(nodes, {
      inDragLayer: opts.inDragLayer
    });
    r.updateCachedGrabbedEles();
  };
  var addNodeToDrag = addNodesToDrag;
  var freeDraggedElements = function freeDraggedElements(grabbedEles) {
    if (!grabbedEles) {
      return;
    }

    // just go over all elements rather than doing a bunch of (possibly expensive) traversals
    r.getCachedZSortedEles().forEach(function (ele) {
      setFreed(ele);
      setOutDragLayer(ele);
      removeGrabTarget(ele);
    });
    r.updateCachedGrabbedEles();
  };

  // helper function to determine which ancestor nodes and edges should go
  // to the drag layer (or should be removed from drag layer).
  var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {
    if (opts.inDragLayer == null && opts.addToList == null) {
      return;
    } // nothing to do

    if (!node.cy().hasCompoundNodes()) {
      return;
    }

    // find top-level parent
    var parent = node.ancestors().orphans();

    // no parent node: no nodes to add to the drag layer
    if (parent.same(node)) {
      return;
    }
    var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());
    var edges = nodes.connectedEdges();
    if (opts.inDragLayer) {
      edges.forEach(setInDragLayer);
      nodes.forEach(setInDragLayer);
    }
    if (opts.addToList) {
      nodes.forEach(function (ele) {
        addToDragList(ele, opts);
      });
    }
  };
  var blurActiveDomElement = function blurActiveDomElement() {
    if (document.activeElement != null && document.activeElement.blur != null) {
      document.activeElement.blur();
    }
  };
  var haveMutationsApi = typeof MutationObserver !== 'undefined';
  var haveResizeObserverApi = typeof ResizeObserver !== 'undefined';

  // watch for when the cy container is removed from the dom
  if (haveMutationsApi) {
    r.removeObserver = new MutationObserver(function (mutns) {
      // eslint-disable-line no-undef
      for (var i = 0; i < mutns.length; i++) {
        var mutn = mutns[i];
        var rNodes = mutn.removedNodes;
        if (rNodes) {
          for (var j = 0; j < rNodes.length; j++) {
            var rNode = rNodes[j];
            if (rNode === r.container) {
              r.destroy();
              break;
            }
          }
        }
      }
    });
    if (r.container.parentNode) {
      r.removeObserver.observe(r.container.parentNode, {
        childList: true
      });
    }
  } else {
    r.registerBinding(r.container, 'DOMNodeRemoved', function (e) {
      // eslint-disable-line no-unused-vars
      r.destroy();
    });
  }
  var onResize = debounce(function () {
    r.cy.resize();
  }, 100);
  if (haveMutationsApi) {
    r.styleObserver = new MutationObserver(onResize); // eslint-disable-line no-undef

    r.styleObserver.observe(r.container, {
      attributes: true
    });
  }

  // auto resize
  r.registerBinding(containerWindow, 'resize', onResize); // eslint-disable-line no-undef

  if (haveResizeObserverApi) {
    r.resizeObserver = new ResizeObserver(onResize); // eslint-disable-line no-undef

    r.resizeObserver.observe(r.container);
  }
  var forEachUp = function forEachUp(domEle, fn) {
    while (domEle != null) {
      fn(domEle);
      domEle = domEle.parentNode;
    }
  };
  var invalidateCoords = function invalidateCoords() {
    r.invalidateContainerClientCoordsCache();
  };
  forEachUp(r.container, function (domEle) {
    r.registerBinding(domEle, 'transitionend', invalidateCoords);
    r.registerBinding(domEle, 'animationend', invalidateCoords);
    r.registerBinding(domEle, 'scroll', invalidateCoords);
  });

  // stop right click menu from appearing on cy
  r.registerBinding(r.container, 'contextmenu', function (e) {
    e.preventDefault();
  });
  var inBoxSelection = function inBoxSelection() {
    return r.selection[4] !== 0;
  };
  var eventInContainer = function eventInContainer(e) {
    // save cycles if mouse events aren't to be captured
    var containerPageCoords = r.findContainerClientCoords();
    var x = containerPageCoords[0];
    var y = containerPageCoords[1];
    var width = containerPageCoords[2];
    var height = containerPageCoords[3];
    var positions = e.touches ? e.touches : [e];
    var atLeastOnePosInside = false;
    for (var i = 0; i < positions.length; i++) {
      var p = positions[i];
      if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {
        atLeastOnePosInside = true;
        break;
      }
    }
    if (!atLeastOnePosInside) {
      return false;
    }
    var container = r.container;
    var target = e.target;
    var tParent = target.parentNode;
    var containerIsTarget = false;
    while (tParent) {
      if (tParent === container) {
        containerIsTarget = true;
        break;
      }
      tParent = tParent.parentNode;
    }
    if (!containerIsTarget) {
      return false;
    } // if target is outisde cy container, then this event is not for us

    return true;
  };

  // Primary key
  r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {
    if (!eventInContainer(e)) {
      return;
    }

    // during left mouse button gestures, ignore other buttons
    if (r.hoverData.which === 1 && e.which !== 1) {
      return;
    }
    e.preventDefault();
    blurActiveDomElement();
    r.hoverData.capture = true;
    r.hoverData.which = e.which;
    var cy = r.cy;
    var gpos = [e.clientX, e.clientY];
    var pos = r.projectIntoViewport(gpos[0], gpos[1]);
    var select = r.selection;
    var nears = r.findNearestElements(pos[0], pos[1], true, false);
    var near = nears[0];
    var draggedElements = r.dragData.possibleDragElements;
    r.hoverData.mdownPos = pos;
    r.hoverData.mdownGPos = gpos;
    var makeEvent = function makeEvent(type) {
      return {
        originalEvent: e,
        type: type,
        position: {
          x: pos[0],
          y: pos[1]
        }
      };
    };
    var checkForTaphold = function checkForTaphold() {
      r.hoverData.tapholdCancelled = false;
      clearTimeout(r.hoverData.tapholdTimeout);
      r.hoverData.tapholdTimeout = setTimeout(function () {
        if (r.hoverData.tapholdCancelled) {
          return;
        } else {
          var ele = r.hoverData.down;
          if (ele) {
            ele.emit(makeEvent('taphold'));
          } else {
            cy.emit(makeEvent('taphold'));
          }
        }
      }, r.tapholdDuration);
    };

    // Right click button
    if (e.which == 3) {
      r.hoverData.cxtStarted = true;
      var cxtEvt = {
        originalEvent: e,
        type: 'cxttapstart',
        position: {
          x: pos[0],
          y: pos[1]
        }
      };
      if (near) {
        near.activate();
        near.emit(cxtEvt);
        r.hoverData.down = near;
      } else {
        cy.emit(cxtEvt);
      }
      r.hoverData.downTime = new Date().getTime();
      r.hoverData.cxtDragged = false;

      // Primary button
    } else if (e.which == 1) {
      if (near) {
        near.activate();
      }

      // Element dragging
      {
        // If something is under the cursor and it is draggable, prepare to grab it
        if (near != null) {
          if (r.nodeIsGrabbable(near)) {
            var triggerGrab = function triggerGrab(ele) {
              ele.emit(makeEvent('grab'));
            };
            setGrabTarget(near);
            if (!near.selected()) {
              draggedElements = r.dragData.possibleDragElements = cy.collection();
              addNodeToDrag(near, {
                addToList: draggedElements
              });
              near.emit(makeEvent('grabon')).emit(makeEvent('grab'));
            } else {
              draggedElements = r.dragData.possibleDragElements = cy.collection();
              var selectedNodes = cy.$(function (ele) {
                return ele.isNode() && ele.selected() && r.nodeIsGrabbable(ele);
              });
              addNodesToDrag(selectedNodes, {
                addToList: draggedElements
              });
              near.emit(makeEvent('grabon'));
              selectedNodes.forEach(triggerGrab);
            }
            r.redrawHint('eles', true);
            r.redrawHint('drag', true);
          }
        }
        r.hoverData.down = near;
        r.hoverData.downs = nears;
        r.hoverData.downTime = new Date().getTime();
      }
      triggerEvents(near, ['mousedown', 'tapstart', 'vmousedown'], e, {
        x: pos[0],
        y: pos[1]
      });
      if (near == null) {
        select[4] = 1;
        r.data.bgActivePosistion = {
          x: pos[0],
          y: pos[1]
        };
        r.redrawHint('select', true);
        r.redraw();
      } else if (near.pannable()) {
        select[4] = 1; // for future pan
      }
      checkForTaphold();
    }

    // Initialize selection box coordinates
    select[0] = select[2] = pos[0];
    select[1] = select[3] = pos[1];
  }, false);
  var shadowRoot = getShadowRoot(r.container);
  r.registerBinding([containerWindow, shadowRoot], 'mousemove', function mousemoveHandler(e) {
    // eslint-disable-line no-undef
    var capture = r.hoverData.capture;
    if (!capture && !eventInContainer(e)) {
      return;
    }
    var preventDefault = false;
    var cy = r.cy;
    var zoom = cy.zoom();
    var gpos = [e.clientX, e.clientY];
    var pos = r.projectIntoViewport(gpos[0], gpos[1]);
    var mdownPos = r.hoverData.mdownPos;
    var mdownGPos = r.hoverData.mdownGPos;
    var select = r.selection;
    var near = null;
    if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {
      near = r.findNearestElement(pos[0], pos[1], true, false);
    }
    var last = r.hoverData.last;
    var down = r.hoverData.down;
    var disp = [pos[0] - select[2], pos[1] - select[3]];
    var draggedElements = r.dragData.possibleDragElements;
    var isOverThresholdDrag;
    if (mdownGPos) {
      var dx = gpos[0] - mdownGPos[0];
      var dx2 = dx * dx;
      var dy = gpos[1] - mdownGPos[1];
      var dy2 = dy * dy;
      var dist2 = dx2 + dy2;
      r.hoverData.isOverThresholdDrag = isOverThresholdDrag = dist2 >= r.desktopTapThreshold2;
    }
    var multSelKeyDown = isMultSelKeyDown(e);
    if (isOverThresholdDrag) {
      r.hoverData.tapholdCancelled = true;
    }
    var updateDragDelta = function updateDragDelta() {
      var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];
      if (dragDelta.length === 0) {
        dragDelta.push(disp[0]);
        dragDelta.push(disp[1]);
      } else {
        dragDelta[0] += disp[0];
        dragDelta[1] += disp[1];
      }
    };
    preventDefault = true;
    triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {
      x: pos[0],
      y: pos[1]
    });
    var makeEvent = function makeEvent(type) {
      return {
        originalEvent: e,
        type: type,
        position: {
          x: pos[0],
          y: pos[1]
        }
      };
    };
    var goIntoBoxMode = function goIntoBoxMode() {
      r.data.bgActivePosistion = undefined;
      if (!r.hoverData.selecting) {
        cy.emit(makeEvent('boxstart'));
      }
      select[4] = 1;
      r.hoverData.selecting = true;
      r.redrawHint('select', true);
      r.redraw();
    };

    // trigger context drag if rmouse down
    if (r.hoverData.which === 3) {
      // but only if over threshold
      if (isOverThresholdDrag) {
        var cxtEvt = makeEvent('cxtdrag');
        if (down) {
          down.emit(cxtEvt);
        } else {
          cy.emit(cxtEvt);
        }
        r.hoverData.cxtDragged = true;
        if (!r.hoverData.cxtOver || near !== r.hoverData.cxtOver) {
          if (r.hoverData.cxtOver) {
            r.hoverData.cxtOver.emit(makeEvent('cxtdragout'));
          }
          r.hoverData.cxtOver = near;
          if (near) {
            near.emit(makeEvent('cxtdragover'));
          }
        }
      }

      // Check if we are drag panning the entire graph
    } else if (r.hoverData.dragging) {
      preventDefault = true;
      if (cy.panningEnabled() && cy.userPanningEnabled()) {
        var deltaP;
        if (r.hoverData.justStartedPan) {
          var mdPos = r.hoverData.mdownPos;
          deltaP = {
            x: (pos[0] - mdPos[0]) * zoom,
            y: (pos[1] - mdPos[1]) * zoom
          };
          r.hoverData.justStartedPan = false;
        } else {
          deltaP = {
            x: disp[0] * zoom,
            y: disp[1] * zoom
          };
        }
        cy.panBy(deltaP);
        cy.emit(makeEvent('dragpan'));
        r.hoverData.dragged = true;
      }

      // Needs reproject due to pan changing viewport
      pos = r.projectIntoViewport(e.clientX, e.clientY);

      // Checks primary button down & out of time & mouse not moved much
    } else if (select[4] == 1 && (down == null || down.pannable())) {
      if (isOverThresholdDrag) {
        if (!r.hoverData.dragging && cy.boxSelectionEnabled() && (multSelKeyDown || !cy.panningEnabled() || !cy.userPanningEnabled())) {
          goIntoBoxMode();
        } else if (!r.hoverData.selecting && cy.panningEnabled() && cy.userPanningEnabled()) {
          var allowPassthrough = allowPanningPassthrough(down, r.hoverData.downs);
          if (allowPassthrough) {
            r.hoverData.dragging = true;
            r.hoverData.justStartedPan = true;
            select[4] = 0;
            r.data.bgActivePosistion = array2point(mdownPos);
            r.redrawHint('select', true);
            r.redraw();
          }
        }
        if (down && down.pannable() && down.active()) {
          down.unactivate();
        }
      }
    } else {
      if (down && down.pannable() && down.active()) {
        down.unactivate();
      }
      if ((!down || !down.grabbed()) && near != last) {
        if (last) {
          triggerEvents(last, ['mouseout', 'tapdragout'], e, {
            x: pos[0],
            y: pos[1]
          });
        }
        if (near) {
          triggerEvents(near, ['mouseover', 'tapdragover'], e, {
            x: pos[0],
            y: pos[1]
          });
        }
        r.hoverData.last = near;
      }
      if (down) {
        if (isOverThresholdDrag) {
          // then we can take action

          if (cy.boxSelectionEnabled() && multSelKeyDown) {
            // then selection overrides
            if (down && down.grabbed()) {
              freeDraggedElements(draggedElements);
              down.emit(makeEvent('freeon'));
              draggedElements.emit(makeEvent('free'));
              if (r.dragData.didDrag) {
                down.emit(makeEvent('dragfreeon'));
                draggedElements.emit(makeEvent('dragfree'));
              }
            }
            goIntoBoxMode();
          } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {
            // drag node
            var justStartedDrag = !r.dragData.didDrag;
            if (justStartedDrag) {
              r.redrawHint('eles', true);
            }
            r.dragData.didDrag = true; // indicate that we actually did drag the node

            // now, add the elements to the drag layer if not done already
            if (!r.hoverData.draggingEles) {
              addNodesToDrag(draggedElements, {
                inDragLayer: true
              });
            }
            var totalShift = {
              x: 0,
              y: 0
            };
            if (number$1(disp[0]) && number$1(disp[1])) {
              totalShift.x += disp[0];
              totalShift.y += disp[1];
              if (justStartedDrag) {
                var dragDelta = r.hoverData.dragDelta;
                if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
                  totalShift.x += dragDelta[0];
                  totalShift.y += dragDelta[1];
                }
              }
            }
            r.hoverData.draggingEles = true;
            draggedElements.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
            r.redrawHint('drag', true);
            r.redraw();
          }
        } else {
          // otherwise save drag delta for when we actually start dragging so the relative grab pos is constant
          updateDragDelta();
        }
      }

      // prevent the dragging from triggering text selection on the page
      preventDefault = true;
    }
    select[2] = pos[0];
    select[3] = pos[1];
    if (preventDefault) {
      if (e.stopPropagation) e.stopPropagation();
      if (e.preventDefault) e.preventDefault();
      return false;
    }
  }, false);
  var clickTimeout, didDoubleClick, prevClickTimeStamp;
  r.registerBinding(containerWindow, 'mouseup', function mouseupHandler(e) {
    // eslint-disable-line no-undef
    // during left mouse button gestures, ignore other buttons
    if (r.hoverData.which === 1 && e.which !== 1 && r.hoverData.capture) {
      return;
    }
    var capture = r.hoverData.capture;
    if (!capture) {
      return;
    }
    r.hoverData.capture = false;
    var cy = r.cy;
    var pos = r.projectIntoViewport(e.clientX, e.clientY);
    var select = r.selection;
    var near = r.findNearestElement(pos[0], pos[1], true, false);
    var draggedElements = r.dragData.possibleDragElements;
    var down = r.hoverData.down;
    var multSelKeyDown = isMultSelKeyDown(e);
    if (r.data.bgActivePosistion) {
      r.redrawHint('select', true);
      r.redraw();
    }
    r.hoverData.tapholdCancelled = true;
    r.data.bgActivePosistion = undefined; // not active bg now

    if (down) {
      down.unactivate();
    }
    var makeEvent = function makeEvent(type) {
      return {
        originalEvent: e,
        type: type,
        position: {
          x: pos[0],
          y: pos[1]
        }
      };
    };
    if (r.hoverData.which === 3) {
      var cxtEvt = makeEvent('cxttapend');
      if (down) {
        down.emit(cxtEvt);
      } else {
        cy.emit(cxtEvt);
      }
      if (!r.hoverData.cxtDragged) {
        var cxtTap = makeEvent('cxttap');
        if (down) {
          down.emit(cxtTap);
        } else {
          cy.emit(cxtTap);
        }
      }
      r.hoverData.cxtDragged = false;
      r.hoverData.which = null;
    } else if (r.hoverData.which === 1) {
      triggerEvents(near, ['mouseup', 'tapend', 'vmouseup'], e, {
        x: pos[0],
        y: pos[1]
      });
      if (!r.dragData.didDrag &&
      // didn't move a node around
      !r.hoverData.dragged &&
      // didn't pan
      !r.hoverData.selecting &&
      // not box selection
      !r.hoverData.isOverThresholdDrag // didn't move too much
      ) {
        triggerEvents(down, ["click", "tap", "vclick"], e, {
          x: pos[0],
          y: pos[1]
        });
        didDoubleClick = false;
        if (e.timeStamp - prevClickTimeStamp <= cy.multiClickDebounceTime()) {
          clickTimeout && clearTimeout(clickTimeout);
          didDoubleClick = true;
          prevClickTimeStamp = null;
          triggerEvents(down, ["dblclick", "dbltap", "vdblclick"], e, {
            x: pos[0],
            y: pos[1]
          });
        } else {
          clickTimeout = setTimeout(function () {
            if (didDoubleClick) return;
            triggerEvents(down, ["oneclick", "onetap", "voneclick"], e, {
              x: pos[0],
              y: pos[1]
            });
          }, cy.multiClickDebounceTime());
          prevClickTimeStamp = e.timeStamp;
        }
      }

      // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something
      if (down == null // not mousedown on node
      && !r.dragData.didDrag // didn't move the node around
      && !r.hoverData.selecting // not box selection
      && !r.hoverData.dragged // didn't pan
      && !isMultSelKeyDown(e)) {
        cy.$(isSelected).unselect(['tapunselect']);
        if (draggedElements.length > 0) {
          r.redrawHint('eles', true);
        }
        r.dragData.possibleDragElements = draggedElements = cy.collection();
      }

      // Single selection
      if (near == down && !r.dragData.didDrag && !r.hoverData.selecting) {
        if (near != null && near._private.selectable) {
          if (r.hoverData.dragging) ; else if (cy.selectionType() === 'additive' || multSelKeyDown) {
            if (near.selected()) {
              near.unselect(['tapunselect']);
            } else {
              near.select(['tapselect']);
            }
          } else {
            if (!multSelKeyDown) {
              cy.$(isSelected).unmerge(near).unselect(['tapunselect']);
              near.select(['tapselect']);
            }
          }
          r.redrawHint('eles', true);
        }
      }
      if (r.hoverData.selecting) {
        var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
        r.redrawHint('select', true);
        if (box.length > 0) {
          r.redrawHint('eles', true);
        }
        cy.emit(makeEvent('boxend'));
        var eleWouldBeSelected = function eleWouldBeSelected(ele) {
          return ele.selectable() && !ele.selected();
        };
        if (cy.selectionType() === 'additive') {
          box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
        } else {
          if (!multSelKeyDown) {
            cy.$(isSelected).unmerge(box).unselect();
          }
          box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
        }

        // always need redraw in case eles unselectable
        r.redraw();
      }

      // Cancel drag pan
      if (r.hoverData.dragging) {
        r.hoverData.dragging = false;
        r.redrawHint('select', true);
        r.redrawHint('eles', true);
        r.redraw();
      }
      if (!select[4]) {
        r.redrawHint('drag', true);
        r.redrawHint('eles', true);
        var downWasGrabbed = down && down.grabbed();
        freeDraggedElements(draggedElements);
        if (downWasGrabbed) {
          down.emit(makeEvent('freeon'));
          draggedElements.emit(makeEvent('free'));
          if (r.dragData.didDrag) {
            down.emit(makeEvent('dragfreeon'));
            draggedElements.emit(makeEvent('dragfree'));
          }
        }
      }
    } // else not right mouse

    select[4] = 0;
    r.hoverData.down = null;
    r.hoverData.cxtStarted = false;
    r.hoverData.draggingEles = false;
    r.hoverData.selecting = false;
    r.hoverData.isOverThresholdDrag = false;
    r.dragData.didDrag = false;
    r.hoverData.dragged = false;
    r.hoverData.dragDelta = [];
    r.hoverData.mdownPos = null;
    r.hoverData.mdownGPos = null;
    r.hoverData.which = null;
  }, false);
  var wheelDeltas = []; // log of first N wheel deltas
  var wheelDeltaN = 4; // how many events to log
  var inaccurateScrollDevice;
  var inaccurateScrollFactor = 100000; // base of inaccurate wheel deltas (e.g. base 5 could yield wheels of 10, 25, 50, etc.)

  var allAreDivisibleBy = function allAreDivisibleBy(list, factor) {
    for (var i = 0; i < list.length; i++) {
      if (list[i] % factor !== 0) {
        return false;
      }
    }
    return true;
  };
  var allAreSameMagnitude = function allAreSameMagnitude(list) {
    var firstMag = Math.abs(list[0]);
    for (var i = 1; i < list.length; i++) {
      if (Math.abs(list[i]) !== firstMag) {
        return false;
      }
    }
    return true;
  };
  var wheelHandler = function wheelHandler(e) {
    var clamp = false;
    var delta = e.deltaY;
    if (delta == null) {
      // compatibility with old browsers
      if (e.wheelDeltaY != null) {
        delta = e.wheelDeltaY / 4;
      } else if (e.wheelDelta != null) {
        delta = e.wheelDelta / 4;
      }
    }
    if (delta === 0) {
      return; // no change in zoom (Bug: Zoom becomes erratic on rapid scroll due to deltaY: 0 event #3394)
    }
    if (inaccurateScrollDevice == null) {
      if (wheelDeltas.length >= wheelDeltaN) {
        // use log to determine if inaccurate
        var wds = wheelDeltas;
        inaccurateScrollDevice = allAreDivisibleBy(wds, 5);
        if (!inaccurateScrollDevice) {
          // check for all large values of exact same magnitude
          var firstMag = Math.abs(wds[0]);
          inaccurateScrollDevice = allAreSameMagnitude(wds) && firstMag > 5;
        }
        if (inaccurateScrollDevice) {
          for (var i = 0; i < wds.length; i++) {
            inaccurateScrollFactor = Math.min(Math.abs(wds[i]), inaccurateScrollFactor);
          }
        }

        // console.log('Sampled wheel deltas:', wds);
        // console.log('inaccurateScrollDevice:', inaccurateScrollDevice);
        // console.log('inaccurateScrollFactor:', inaccurateScrollFactor);
      } else {
        // clamp and log until we reach N
        wheelDeltas.push(delta);
        clamp = true;
        // console.log('Clamping initial wheel events until we get a good sample');
      }
    } else if (inaccurateScrollDevice) {
      // keep updating
      inaccurateScrollFactor = Math.min(Math.abs(delta), inaccurateScrollFactor);
      // console.log('Keep updating inaccurateScrollFactor beyond sample in case we did not get the smallest possible val:', inaccurateScrollFactor);
    }
    if (r.scrollingPage) {
      return;
    } // while scrolling, ignore wheel-to-zoom

    var cy = r.cy;
    var zoom = cy.zoom();
    var pan = cy.pan();
    var pos = r.projectIntoViewport(e.clientX, e.clientY);
    var rpos = [pos[0] * zoom + pan.x, pos[1] * zoom + pan.y];
    if (r.hoverData.draggingEles || r.hoverData.dragging || r.hoverData.cxtStarted || inBoxSelection()) {
      // if pan dragging or cxt dragging, wheel movements make no zoom
      e.preventDefault();
      return;
    }
    if (cy.panningEnabled() && cy.userPanningEnabled() && cy.zoomingEnabled() && cy.userZoomingEnabled()) {
      e.preventDefault();
      r.data.wheelZooming = true;
      clearTimeout(r.data.wheelTimeout);
      r.data.wheelTimeout = setTimeout(function () {
        r.data.wheelZooming = false;
        r.redrawHint('eles', true);
        r.redraw();
      }, 150);
      var diff;
      if (clamp && Math.abs(delta) > 5) {
        delta = signum(delta) * 5;
      }
      diff = delta / -250;
      if (inaccurateScrollDevice) {
        diff /= inaccurateScrollFactor;
        diff *= 3;
      }
      diff = diff * r.wheelSensitivity;

      // console.log(`delta = ${delta}, diff = ${diff}, mode = ${e.deltaMode}`)

      var needsWheelFix = e.deltaMode === 1;
      if (needsWheelFix) {
        // fixes slow wheel events on ff/linux and ff/windows
        diff *= 33;
      }
      var newZoom = cy.zoom() * Math.pow(10, diff);
      if (e.type === 'gesturechange') {
        newZoom = r.gestureStartZoom * e.scale;
      }
      cy.zoom({
        level: newZoom,
        renderedPosition: {
          x: rpos[0],
          y: rpos[1]
        }
      });
      cy.emit({
        type: e.type === 'gesturechange' ? 'pinchzoom' : 'scrollzoom',
        originalEvent: e,
        position: {
          x: pos[0],
          y: pos[1]
        }
      });
    }
  };

  // Functions to help with whether mouse wheel should trigger zooming
  // --
  r.registerBinding(r.container, 'wheel', wheelHandler, true);

  // disable nonstandard wheel events
  // r.registerBinding(r.container, 'mousewheel', wheelHandler, true);
  // r.registerBinding(r.container, 'DOMMouseScroll', wheelHandler, true);
  // r.registerBinding(r.container, 'MozMousePixelScroll', wheelHandler, true); // older firefox

  r.registerBinding(containerWindow, 'scroll', function scrollHandler(e) {
    // eslint-disable-line no-unused-vars
    r.scrollingPage = true;
    clearTimeout(r.scrollingPageTimeout);
    r.scrollingPageTimeout = setTimeout(function () {
      r.scrollingPage = false;
    }, 250);
  }, true);

  // desktop safari pinch to zoom start
  r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {
    r.gestureStartZoom = r.cy.zoom();
    if (!r.hasTouchStarted) {
      // don't affect touch devices like iphone
      e.preventDefault();
    }
  }, true);
  r.registerBinding(r.container, 'gesturechange', function (e) {
    if (!r.hasTouchStarted) {
      // don't affect touch devices like iphone
      wheelHandler(e);
    }
  }, true);

  // Functions to help with handling mouseout/mouseover on the Cytoscape container
  // Handle mouseout on Cytoscape container
  r.registerBinding(r.container, 'mouseout', function mouseOutHandler(e) {
    var pos = r.projectIntoViewport(e.clientX, e.clientY);
    r.cy.emit({
      originalEvent: e,
      type: 'mouseout',
      position: {
        x: pos[0],
        y: pos[1]
      }
    });
  }, false);
  r.registerBinding(r.container, 'mouseover', function mouseOverHandler(e) {
    var pos = r.projectIntoViewport(e.clientX, e.clientY);
    r.cy.emit({
      originalEvent: e,
      type: 'mouseover',
      position: {
        x: pos[0],
        y: pos[1]
      }
    });
  }, false);
  var f1x1, f1y1, f2x1, f2y1; // starting points for pinch-to-zoom
  var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom
  var center1, modelCenter1; // center point on start pinch to zoom
  var offsetLeft, offsetTop;
  var containerWidth, containerHeight;
  var twoFingersStartInside;
  var distance = function distance(x1, y1, x2, y2) {
    return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  };
  var distanceSq = function distanceSq(x1, y1, x2, y2) {
    return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
  };
  var touchstartHandler;
  r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {
    r.hasTouchStarted = true;
    if (!eventInContainer(e)) {
      return;
    }
    blurActiveDomElement();
    r.touchData.capture = true;
    r.data.bgActivePosistion = undefined;
    var cy = r.cy;
    var now = r.touchData.now;
    var earlier = r.touchData.earlier;
    if (e.touches[0]) {
      var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
      now[0] = pos[0];
      now[1] = pos[1];
    }
    if (e.touches[1]) {
      var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
      now[2] = pos[0];
      now[3] = pos[1];
    }
    if (e.touches[2]) {
      var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
      now[4] = pos[0];
      now[5] = pos[1];
    }
    var makeEvent = function makeEvent(type) {
      return {
        originalEvent: e,
        type: type,
        position: {
          x: now[0],
          y: now[1]
        }
      };
    };

    // record starting points for pinch-to-zoom
    if (e.touches[1]) {
      r.touchData.singleTouchMoved = true;
      freeDraggedElements(r.dragData.touchDragEles);
      var offsets = r.findContainerClientCoords();
      offsetLeft = offsets[0];
      offsetTop = offsets[1];
      containerWidth = offsets[2];
      containerHeight = offsets[3];
      f1x1 = e.touches[0].clientX - offsetLeft;
      f1y1 = e.touches[0].clientY - offsetTop;
      f2x1 = e.touches[1].clientX - offsetLeft;
      f2y1 = e.touches[1].clientY - offsetTop;
      twoFingersStartInside = 0 <= f1x1 && f1x1 <= containerWidth && 0 <= f2x1 && f2x1 <= containerWidth && 0 <= f1y1 && f1y1 <= containerHeight && 0 <= f2y1 && f2y1 <= containerHeight;
      var pan = cy.pan();
      var zoom = cy.zoom();
      distance1 = distance(f1x1, f1y1, f2x1, f2y1);
      distance1Sq = distanceSq(f1x1, f1y1, f2x1, f2y1);
      center1 = [(f1x1 + f2x1) / 2, (f1y1 + f2y1) / 2];
      modelCenter1 = [(center1[0] - pan.x) / zoom, (center1[1] - pan.y) / zoom];

      // consider context tap
      var cxtDistThreshold = 200;
      var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;
      if (distance1Sq < cxtDistThresholdSq && !e.touches[2]) {
        var near1 = r.findNearestElement(now[0], now[1], true, true);
        var near2 = r.findNearestElement(now[2], now[3], true, true);
        if (near1 && near1.isNode()) {
          near1.activate().emit(makeEvent('cxttapstart'));
          r.touchData.start = near1;
        } else if (near2 && near2.isNode()) {
          near2.activate().emit(makeEvent('cxttapstart'));
          r.touchData.start = near2;
        } else {
          cy.emit(makeEvent('cxttapstart'));
        }
        if (r.touchData.start) {
          r.touchData.start._private.grabbed = false;
        }
        r.touchData.cxt = true;
        r.touchData.cxtDragged = false;
        r.data.bgActivePosistion = undefined;
        r.redraw();
        return;
      }
    }
    if (e.touches[2]) {
      // ignore

      // safari on ios pans the page otherwise (normally you should be able to preventdefault on touchmove...)
      if (cy.boxSelectionEnabled()) {
        e.preventDefault();
      }
    } else if (e.touches[1]) ; else if (e.touches[0]) {
      var nears = r.findNearestElements(now[0], now[1], true, true);
      var near = nears[0];
      if (near != null) {
        near.activate();
        r.touchData.start = near;
        r.touchData.starts = nears;
        if (r.nodeIsGrabbable(near)) {
          var draggedEles = r.dragData.touchDragEles = cy.collection();
          var selectedNodes = null;
          r.redrawHint('eles', true);
          r.redrawHint('drag', true);
          if (near.selected()) {
            // reset drag elements, since near will be added again

            selectedNodes = cy.$(function (ele) {
              return ele.selected() && r.nodeIsGrabbable(ele);
            });
            addNodesToDrag(selectedNodes, {
              addToList: draggedEles
            });
          } else {
            addNodeToDrag(near, {
              addToList: draggedEles
            });
          }
          setGrabTarget(near);
          near.emit(makeEvent('grabon'));
          if (selectedNodes) {
            selectedNodes.forEach(function (n) {
              n.emit(makeEvent('grab'));
            });
          } else {
            near.emit(makeEvent('grab'));
          }
        }
      }
      triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {
        x: now[0],
        y: now[1]
      });
      if (near == null) {
        r.data.bgActivePosistion = {
          x: pos[0],
          y: pos[1]
        };
        r.redrawHint('select', true);
        r.redraw();
      }

      // Tap, taphold
      // -----

      r.touchData.singleTouchMoved = false;
      r.touchData.singleTouchStartTime = +new Date();
      clearTimeout(r.touchData.tapholdTimeout);
      r.touchData.tapholdTimeout = setTimeout(function () {
        if (r.touchData.singleTouchMoved === false && !r.pinching // if pinching, then taphold unselect shouldn't take effect
        && !r.touchData.selecting // box selection shouldn't allow taphold through
        ) {
          triggerEvents(r.touchData.start, ['taphold'], e, {
            x: now[0],
            y: now[1]
          });
        }
      }, r.tapholdDuration);
    }
    if (e.touches.length >= 1) {
      var sPos = r.touchData.startPosition = [null, null, null, null, null, null];
      for (var i = 0; i < now.length; i++) {
        sPos[i] = earlier[i] = now[i];
      }
      var touch0 = e.touches[0];
      r.touchData.startGPosition = [touch0.clientX, touch0.clientY];
    }
  }, false);
  var touchmoveHandler;
  r.registerBinding(containerWindow, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {
    // eslint-disable-line no-undef
    var capture = r.touchData.capture;
    if (!capture && !eventInContainer(e)) {
      return;
    }
    var select = r.selection;
    var cy = r.cy;
    var now = r.touchData.now;
    var earlier = r.touchData.earlier;
    var zoom = cy.zoom();
    if (e.touches[0]) {
      var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
      now[0] = pos[0];
      now[1] = pos[1];
    }
    if (e.touches[1]) {
      var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
      now[2] = pos[0];
      now[3] = pos[1];
    }
    if (e.touches[2]) {
      var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
      now[4] = pos[0];
      now[5] = pos[1];
    }
    var makeEvent = function makeEvent(type) {
      return {
        originalEvent: e,
        type: type,
        position: {
          x: now[0],
          y: now[1]
        }
      };
    };
    var startGPos = r.touchData.startGPosition;
    var isOverThresholdDrag;
    if (capture && e.touches[0] && startGPos) {
      var disp = [];
      for (var j = 0; j < now.length; j++) {
        disp[j] = now[j] - earlier[j];
      }
      var dx = e.touches[0].clientX - startGPos[0];
      var dx2 = dx * dx;
      var dy = e.touches[0].clientY - startGPos[1];
      var dy2 = dy * dy;
      var dist2 = dx2 + dy2;
      isOverThresholdDrag = dist2 >= r.touchTapThreshold2;
    }

    // context swipe cancelling
    if (capture && r.touchData.cxt) {
      e.preventDefault();
      var f1x2 = e.touches[0].clientX - offsetLeft,
        f1y2 = e.touches[0].clientY - offsetTop;
      var f2x2 = e.touches[1].clientX - offsetLeft,
        f2y2 = e.touches[1].clientY - offsetTop;
      // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );
      var distance2Sq = distanceSq(f1x2, f1y2, f2x2, f2y2);
      var factorSq = distance2Sq / distance1Sq;
      var distThreshold = 150;
      var distThresholdSq = distThreshold * distThreshold;
      var factorThreshold = 1.5;
      var factorThresholdSq = factorThreshold * factorThreshold;

      // cancel ctx gestures if the distance b/t the fingers increases
      if (factorSq >= factorThresholdSq || distance2Sq >= distThresholdSq) {
        r.touchData.cxt = false;
        r.data.bgActivePosistion = undefined;
        r.redrawHint('select', true);
        var cxtEvt = makeEvent('cxttapend');
        if (r.touchData.start) {
          r.touchData.start.unactivate().emit(cxtEvt);
          r.touchData.start = null;
        } else {
          cy.emit(cxtEvt);
        }
      }
    }

    // context swipe
    if (capture && r.touchData.cxt) {
      var cxtEvt = makeEvent('cxtdrag');
      r.data.bgActivePosistion = undefined;
      r.redrawHint('select', true);
      if (r.touchData.start) {
        r.touchData.start.emit(cxtEvt);
      } else {
        cy.emit(cxtEvt);
      }
      if (r.touchData.start) {
        r.touchData.start._private.grabbed = false;
      }
      r.touchData.cxtDragged = true;
      var near = r.findNearestElement(now[0], now[1], true, true);
      if (!r.touchData.cxtOver || near !== r.touchData.cxtOver) {
        if (r.touchData.cxtOver) {
          r.touchData.cxtOver.emit(makeEvent('cxtdragout'));
        }
        r.touchData.cxtOver = near;
        if (near) {
          near.emit(makeEvent('cxtdragover'));
        }
      }

      // box selection
    } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {
      e.preventDefault();
      r.data.bgActivePosistion = undefined;
      this.lastThreeTouch = +new Date();
      if (!r.touchData.selecting) {
        cy.emit(makeEvent('boxstart'));
      }
      r.touchData.selecting = true;
      r.touchData.didSelect = true;
      select[4] = 1;
      if (!select || select.length === 0 || select[0] === undefined) {
        select[0] = (now[0] + now[2] + now[4]) / 3;
        select[1] = (now[1] + now[3] + now[5]) / 3;
        select[2] = (now[0] + now[2] + now[4]) / 3 + 1;
        select[3] = (now[1] + now[3] + now[5]) / 3 + 1;
      } else {
        select[2] = (now[0] + now[2] + now[4]) / 3;
        select[3] = (now[1] + now[3] + now[5]) / 3;
      }
      r.redrawHint('select', true);
      r.redraw();

      // pinch to zoom
    } else if (capture && e.touches[1] && !r.touchData.didSelect // don't allow box selection to degrade to pinch-to-zoom
    && cy.zoomingEnabled() && cy.panningEnabled() && cy.userZoomingEnabled() && cy.userPanningEnabled()) {
      // two fingers => pinch to zoom
      e.preventDefault();
      r.data.bgActivePosistion = undefined;
      r.redrawHint('select', true);
      var draggedEles = r.dragData.touchDragEles;
      if (draggedEles) {
        r.redrawHint('drag', true);
        for (var i = 0; i < draggedEles.length; i++) {
          var de_p = draggedEles[i]._private;
          de_p.grabbed = false;
          de_p.rscratch.inDragLayer = false;
        }
      }
      var _start = r.touchData.start;

      // (x2, y2) for fingers 1 and 2
      var f1x2 = e.touches[0].clientX - offsetLeft,
        f1y2 = e.touches[0].clientY - offsetTop;
      var f2x2 = e.touches[1].clientX - offsetLeft,
        f2y2 = e.touches[1].clientY - offsetTop;
      var distance2 = distance(f1x2, f1y2, f2x2, f2y2);
      // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );
      // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );
      var factor = distance2 / distance1;
      if (twoFingersStartInside) {
        // delta finger1
        var df1x = f1x2 - f1x1;
        var df1y = f1y2 - f1y1;

        // delta finger 2
        var df2x = f2x2 - f2x1;
        var df2y = f2y2 - f2y1;

        // translation is the normalised vector of the two fingers movement
        // i.e. so pinching cancels out and moving together pans
        var tx = (df1x + df2x) / 2;
        var ty = (df1y + df2y) / 2;

        // now calculate the zoom
        var zoom1 = cy.zoom();
        var zoom2 = zoom1 * factor;
        var pan1 = cy.pan();

        // the model center point converted to the current rendered pos
        var ctrx = modelCenter1[0] * zoom1 + pan1.x;
        var ctry = modelCenter1[1] * zoom1 + pan1.y;
        var pan2 = {
          x: -zoom2 / zoom1 * (ctrx - pan1.x - tx) + ctrx,
          y: -zoom2 / zoom1 * (ctry - pan1.y - ty) + ctry
        };

        // remove dragged eles
        if (_start && _start.active()) {
          var draggedEles = r.dragData.touchDragEles;
          freeDraggedElements(draggedEles);
          r.redrawHint('drag', true);
          r.redrawHint('eles', true);
          _start.unactivate().emit(makeEvent('freeon'));
          draggedEles.emit(makeEvent('free'));
          if (r.dragData.didDrag) {
            _start.emit(makeEvent('dragfreeon'));
            draggedEles.emit(makeEvent('dragfree'));
          }
        }
        cy.viewport({
          zoom: zoom2,
          pan: pan2,
          cancelOnFailedZoom: true
        });
        cy.emit(makeEvent('pinchzoom'));
        distance1 = distance2;
        f1x1 = f1x2;
        f1y1 = f1y2;
        f2x1 = f2x2;
        f2y1 = f2y2;
        r.pinching = true;
      }

      // Re-project
      if (e.touches[0]) {
        var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
        now[0] = pos[0];
        now[1] = pos[1];
      }
      if (e.touches[1]) {
        var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
        now[2] = pos[0];
        now[3] = pos[1];
      }
      if (e.touches[2]) {
        var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
        now[4] = pos[0];
        now[5] = pos[1];
      }
    } else if (e.touches[0] && !r.touchData.didSelect // don't allow box selection to degrade to single finger events like panning
    ) {
      var start = r.touchData.start;
      var last = r.touchData.last;
      var near;
      if (!r.hoverData.draggingEles && !r.swipePanning) {
        near = r.findNearestElement(now[0], now[1], true, true);
      }
      if (capture && start != null) {
        e.preventDefault();
      }

      // dragging nodes
      if (capture && start != null && r.nodeIsDraggable(start)) {
        if (isOverThresholdDrag) {
          // then dragging can happen
          var draggedEles = r.dragData.touchDragEles;
          var justStartedDrag = !r.dragData.didDrag;
          if (justStartedDrag) {
            addNodesToDrag(draggedEles, {
              inDragLayer: true
            });
          }
          r.dragData.didDrag = true;
          var totalShift = {
            x: 0,
            y: 0
          };
          if (number$1(disp[0]) && number$1(disp[1])) {
            totalShift.x += disp[0];
            totalShift.y += disp[1];
            if (justStartedDrag) {
              r.redrawHint('eles', true);
              var dragDelta = r.touchData.dragDelta;
              if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
                totalShift.x += dragDelta[0];
                totalShift.y += dragDelta[1];
              }
            }
          }
          r.hoverData.draggingEles = true;
          draggedEles.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
          r.redrawHint('drag', true);
          if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {
            r.redrawHint('eles', true);
          }
          r.redraw();
        } else {
          // otherwise keep track of drag delta for later
          var dragDelta = r.touchData.dragDelta = r.touchData.dragDelta || [];
          if (dragDelta.length === 0) {
            dragDelta.push(disp[0]);
            dragDelta.push(disp[1]);
          } else {
            dragDelta[0] += disp[0];
            dragDelta[1] += disp[1];
          }
        }
      }

      // touchmove
      {
        triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {
          x: now[0],
          y: now[1]
        });
        if ((!start || !start.grabbed()) && near != last) {
          if (last) {
            last.emit(makeEvent('tapdragout'));
          }
          if (near) {
            near.emit(makeEvent('tapdragover'));
          }
        }
        r.touchData.last = near;
      }

      // check to cancel taphold
      if (capture) {
        for (var i = 0; i < now.length; i++) {
          if (now[i] && r.touchData.startPosition[i] && isOverThresholdDrag) {
            r.touchData.singleTouchMoved = true;
          }
        }
      }

      // panning
      if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {
        var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);
        if (allowPassthrough) {
          e.preventDefault();
          if (!r.data.bgActivePosistion) {
            r.data.bgActivePosistion = array2point(r.touchData.startPosition);
          }
          if (r.swipePanning) {
            cy.panBy({
              x: disp[0] * zoom,
              y: disp[1] * zoom
            });
            cy.emit(makeEvent('dragpan'));
          } else if (isOverThresholdDrag) {
            r.swipePanning = true;
            cy.panBy({
              x: dx * zoom,
              y: dy * zoom
            });
            cy.emit(makeEvent('dragpan'));
            if (start) {
              start.unactivate();
              r.redrawHint('select', true);
              r.touchData.start = null;
            }
          }
        }

        // Re-project
        var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
        now[0] = pos[0];
        now[1] = pos[1];
      }
    }
    for (var j = 0; j < now.length; j++) {
      earlier[j] = now[j];
    }

    // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning
    if (capture && e.touches.length > 0 && !r.hoverData.draggingEles && !r.swipePanning && r.data.bgActivePosistion != null) {
      r.data.bgActivePosistion = undefined;
      r.redrawHint('select', true);
      r.redraw();
    }
  }, false);
  var touchcancelHandler;
  r.registerBinding(containerWindow, 'touchcancel', touchcancelHandler = function touchcancelHandler(e) {
    // eslint-disable-line no-unused-vars
    var start = r.touchData.start;
    r.touchData.capture = false;
    if (start) {
      start.unactivate();
    }
  });
  var touchendHandler, didDoubleTouch, touchTimeout, prevTouchTimeStamp;
  r.registerBinding(containerWindow, 'touchend', touchendHandler = function touchendHandler(e) {
    // eslint-disable-line no-unused-vars
    var start = r.touchData.start;
    var capture = r.touchData.capture;
    if (capture) {
      if (e.touches.length === 0) {
        r.touchData.capture = false;
      }
      e.preventDefault();
    } else {
      return;
    }
    var select = r.selection;
    r.swipePanning = false;
    r.hoverData.draggingEles = false;
    var cy = r.cy;
    var zoom = cy.zoom();
    var now = r.touchData.now;
    var earlier = r.touchData.earlier;
    if (e.touches[0]) {
      var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
      now[0] = pos[0];
      now[1] = pos[1];
    }
    if (e.touches[1]) {
      var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
      now[2] = pos[0];
      now[3] = pos[1];
    }
    if (e.touches[2]) {
      var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
      now[4] = pos[0];
      now[5] = pos[1];
    }
    var makeEvent = function makeEvent(type) {
      return {
        originalEvent: e,
        type: type,
        position: {
          x: now[0],
          y: now[1]
        }
      };
    };
    if (start) {
      start.unactivate();
    }
    var ctxTapend;
    if (r.touchData.cxt) {
      ctxTapend = makeEvent('cxttapend');
      if (start) {
        start.emit(ctxTapend);
      } else {
        cy.emit(ctxTapend);
      }
      if (!r.touchData.cxtDragged) {
        var ctxTap = makeEvent('cxttap');
        if (start) {
          start.emit(ctxTap);
        } else {
          cy.emit(ctxTap);
        }
      }
      if (r.touchData.start) {
        r.touchData.start._private.grabbed = false;
      }
      r.touchData.cxt = false;
      r.touchData.start = null;
      r.redraw();
      return;
    }

    // no more box selection if we don't have three fingers
    if (!e.touches[2] && cy.boxSelectionEnabled() && r.touchData.selecting) {
      r.touchData.selecting = false;
      var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
      select[0] = undefined;
      select[1] = undefined;
      select[2] = undefined;
      select[3] = undefined;
      select[4] = 0;
      r.redrawHint('select', true);
      cy.emit(makeEvent('boxend'));
      var eleWouldBeSelected = function eleWouldBeSelected(ele) {
        return ele.selectable() && !ele.selected();
      };
      box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
      if (box.nonempty()) {
        r.redrawHint('eles', true);
      }
      r.redraw();
    }
    if (start != null) {
      start.unactivate();
    }
    if (e.touches[2]) {
      r.data.bgActivePosistion = undefined;
      r.redrawHint('select', true);
    } else if (e.touches[1]) ; else if (e.touches[0]) ; else if (!e.touches[0]) {
      r.data.bgActivePosistion = undefined;
      r.redrawHint('select', true);
      var draggedEles = r.dragData.touchDragEles;
      if (start != null) {
        var startWasGrabbed = start._private.grabbed;
        freeDraggedElements(draggedEles);
        r.redrawHint('drag', true);
        r.redrawHint('eles', true);
        if (startWasGrabbed) {
          start.emit(makeEvent('freeon'));
          draggedEles.emit(makeEvent('free'));
          if (r.dragData.didDrag) {
            start.emit(makeEvent('dragfreeon'));
            draggedEles.emit(makeEvent('dragfree'));
          }
        }
        triggerEvents(start, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
          x: now[0],
          y: now[1]
        });
        start.unactivate();
        r.touchData.start = null;
      } else {
        var near = r.findNearestElement(now[0], now[1], true, true);
        triggerEvents(near, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
          x: now[0],
          y: now[1]
        });
      }
      var dx = r.touchData.startPosition[0] - now[0];
      var dx2 = dx * dx;
      var dy = r.touchData.startPosition[1] - now[1];
      var dy2 = dy * dy;
      var dist2 = dx2 + dy2;
      var rdist2 = dist2 * zoom * zoom;

      // Tap event, roughly same as mouse click event for touch
      if (!r.touchData.singleTouchMoved) {
        if (!start) {
          cy.$(':selected').unselect(['tapunselect']);
        }
        triggerEvents(start, ['tap', 'vclick'], e, {
          x: now[0],
          y: now[1]
        });
        didDoubleTouch = false;
        if (e.timeStamp - prevTouchTimeStamp <= cy.multiClickDebounceTime()) {
          touchTimeout && clearTimeout(touchTimeout);
          didDoubleTouch = true;
          prevTouchTimeStamp = null;
          triggerEvents(start, ['dbltap', 'vdblclick'], e, {
            x: now[0],
            y: now[1]
          });
        } else {
          touchTimeout = setTimeout(function () {
            if (didDoubleTouch) return;
            triggerEvents(start, ['onetap', 'voneclick'], e, {
              x: now[0],
              y: now[1]
            });
          }, cy.multiClickDebounceTime());
          prevTouchTimeStamp = e.timeStamp;
        }
      }

      // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance
      if (start != null && !r.dragData.didDrag // didn't drag nodes around
      && start._private.selectable && rdist2 < r.touchTapThreshold2 && !r.pinching // pinch to zoom should not affect selection
      ) {
        if (cy.selectionType() === 'single') {
          cy.$(isSelected).unmerge(start).unselect(['tapunselect']);
          start.select(['tapselect']);
        } else {
          if (start.selected()) {
            start.unselect(['tapunselect']);
          } else {
            start.select(['tapselect']);
          }
        }
        r.redrawHint('eles', true);
      }
      r.touchData.singleTouchMoved = true;
    }
    for (var j = 0; j < now.length; j++) {
      earlier[j] = now[j];
    }
    r.dragData.didDrag = false; // reset for next touchstart

    if (e.touches.length === 0) {
      r.touchData.dragDelta = [];
      r.touchData.startPosition = [null, null, null, null, null, null];
      r.touchData.startGPosition = null;
      r.touchData.didSelect = false;
    }
    if (e.touches.length < 2) {
      if (e.touches.length === 1) {
        // the old start global pos'n may not be the same finger that remains
        r.touchData.startGPosition = [e.touches[0].clientX, e.touches[0].clientY];
      }
      r.pinching = false;
      r.redrawHint('eles', true);
      r.redraw();
    }

    //r.redraw();
  }, false);

  // fallback compatibility layer for ms pointer events
  if (typeof TouchEvent === 'undefined') {
    var pointers = [];
    var makeTouch = function makeTouch(e) {
      return {
        clientX: e.clientX,
        clientY: e.clientY,
        force: 1,
        identifier: e.pointerId,
        pageX: e.pageX,
        pageY: e.pageY,
        radiusX: e.width / 2,
        radiusY: e.height / 2,
        screenX: e.screenX,
        screenY: e.screenY,
        target: e.target
      };
    };
    var makePointer = function makePointer(e) {
      return {
        event: e,
        touch: makeTouch(e)
      };
    };
    var addPointer = function addPointer(e) {
      pointers.push(makePointer(e));
    };
    var removePointer = function removePointer(e) {
      for (var i = 0; i < pointers.length; i++) {
        var p = pointers[i];
        if (p.event.pointerId === e.pointerId) {
          pointers.splice(i, 1);
          return;
        }
      }
    };
    var updatePointer = function updatePointer(e) {
      var p = pointers.filter(function (p) {
        return p.event.pointerId === e.pointerId;
      })[0];
      p.event = e;
      p.touch = makeTouch(e);
    };
    var addTouchesToEvent = function addTouchesToEvent(e) {
      e.touches = pointers.map(function (p) {
        return p.touch;
      });
    };
    var pointerIsMouse = function pointerIsMouse(e) {
      return e.pointerType === 'mouse' || e.pointerType === 4;
    };
    r.registerBinding(r.container, 'pointerdown', function (e) {
      if (pointerIsMouse(e)) {
        return;
      } // mouse already handled

      e.preventDefault();
      addPointer(e);
      addTouchesToEvent(e);
      touchstartHandler(e);
    });
    r.registerBinding(r.container, 'pointerup', function (e) {
      if (pointerIsMouse(e)) {
        return;
      } // mouse already handled

      removePointer(e);
      addTouchesToEvent(e);
      touchendHandler(e);
    });
    r.registerBinding(r.container, 'pointercancel', function (e) {
      if (pointerIsMouse(e)) {
        return;
      } // mouse already handled

      removePointer(e);
      addTouchesToEvent(e);
      touchcancelHandler(e);
    });
    r.registerBinding(r.container, 'pointermove', function (e) {
      if (pointerIsMouse(e)) {
        return;
      } // mouse already handled

      e.preventDefault();
      updatePointer(e);
      addTouchesToEvent(e);
      touchmoveHandler(e);
    });
  }
};

var BRp$2 = {};
BRp$2.generatePolygon = function (name, points) {
  return this.nodeShapes[name] = {
    renderer: this,
    name: name,
    points: points,
    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
      this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
      return polygonIntersectLine(x, y, this.points, nodeX, nodeY, width / 2, height / 2, padding);
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
      return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);
    },
    hasMiterBounds: name !== 'rectangle',
    miterBounds: function miterBounds(centerX, centerY, width, height, strokeWidth, strokePosition) {
      return miterBox(this.points, centerX, centerY, width, height, strokeWidth);
    }
  };
};
BRp$2.generateEllipse = function () {
  return this.nodeShapes['ellipse'] = {
    renderer: this,
    name: 'ellipse',
    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
      return intersectLineEllipse(x, y, nodeX, nodeY, width / 2 + padding, height / 2 + padding);
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
      return checkInEllipse(x, y, width, height, centerX, centerY, padding);
    }
  };
};
BRp$2.generateRoundPolygon = function (name, points) {
  return this.nodeShapes[name] = {
    renderer: this,
    name: name,
    points: points,
    getOrCreateCorners: function getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, field) {
      if (rs[field] !== undefined && rs[field + '-cx'] === centerX && rs[field + '-cy'] === centerY) {
        return rs[field];
      }
      rs[field] = new Array(points.length / 2);
      rs[field + '-cx'] = centerX;
      rs[field + '-cy'] = centerY;
      var halfW = width / 2;
      var halfH = height / 2;
      cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(width, height) : cornerRadius;
      var p = new Array(points.length / 2);
      for (var _i = 0; _i < points.length / 2; _i++) {
        p[_i] = {
          x: centerX + halfW * points[_i * 2],
          y: centerY + halfH * points[_i * 2 + 1]
        };
      }
      var i,
        p1,
        p2,
        p3,
        len = p.length;
      p1 = p[len - 1];
      // for each point
      for (i = 0; i < len; i++) {
        p2 = p[i % len];
        p3 = p[(i + 1) % len];
        rs[field][i] = getRoundCorner(p1, p2, p3, cornerRadius);
        p1 = p2;
        p2 = p3;
      }
      return rs[field];
    },
    draw: function draw(context, centerX, centerY, width, height, cornerRadius, rs) {
      this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'drawCorners'));
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius, rs) {
      return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height, padding, this.getOrCreateCorners(nodeX, nodeY, width, height, cornerRadius, rs, 'corners'));
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius, rs) {
      return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'corners'));
    }
  };
};
BRp$2.generateRoundRectangle = function () {
  return this.nodeShapes['round-rectangle'] = this.nodeShapes['roundrectangle'] = {
    renderer: this,
    name: 'round-rectangle',
    points: generateUnitNgonPointsFitToSquare(4, 0),
    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
      return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
      var halfWidth = width / 2;
      var halfHeight = height / 2;
      cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
      cornerRadius = Math.min(halfWidth, halfHeight, cornerRadius);
      var diam = cornerRadius * 2;

      // Check hBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
        return true;
      }

      // Check vBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
        return true;
      }

      // Check top left quarter circle
      if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
        return true;
      }

      // Check top right quarter circle
      if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
        return true;
      }

      // Check bottom right quarter circle
      if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
        return true;
      }

      // Check bottom left quarter circle
      if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
        return true;
      }
      return false;
    }
  };
};
BRp$2.generateCutRectangle = function () {
  return this.nodeShapes['cut-rectangle'] = this.nodeShapes['cutrectangle'] = {
    renderer: this,
    name: 'cut-rectangle',
    cornerLength: getCutRectangleCornerLength(),
    points: generateUnitNgonPointsFitToSquare(4, 0),
    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, null, cornerRadius);
    },
    generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY, cornerRadius) {
      var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
      var hh = height / 2;
      var hw = width / 2;
      var xBegin = centerX - hw;
      var xEnd = centerX + hw;
      var yBegin = centerY - hh;
      var yEnd = centerY + hh;

      // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]
      return {
        topLeft: [xBegin, yBegin + cl, xBegin + cl, yBegin, xBegin + cl, yBegin + cl],
        topRight: [xEnd - cl, yBegin, xEnd, yBegin + cl, xEnd - cl, yBegin + cl],
        bottomRight: [xEnd, yEnd - cl, xEnd - cl, yEnd, xEnd - cl, yEnd - cl],
        bottomLeft: [xBegin + cl, yEnd, xBegin, yEnd - cl, xBegin + cl, yEnd - cl]
      };
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
      var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY, cornerRadius);
      var pts = [].concat.apply([], [cPts.topLeft.splice(0, 4), cPts.topRight.splice(0, 4), cPts.bottomRight.splice(0, 4), cPts.bottomLeft.splice(0, 4)]);
      return polygonIntersectLine(x, y, pts, nodeX, nodeY);
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
      var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
      // Check hBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * cl, [0, -1], padding)) {
        return true;
      }

      // Check vBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * cl, height, [0, -1], padding)) {
        return true;
      }
      var cutTrianglePts = this.generateCutTrianglePts(width, height, centerX, centerY);
      return pointInsidePolygonPoints(x, y, cutTrianglePts.topLeft) || pointInsidePolygonPoints(x, y, cutTrianglePts.topRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomLeft);
    }
  };
};
BRp$2.generateBarrel = function () {
  return this.nodeShapes['barrel'] = {
    renderer: this,
    name: 'barrel',
    points: generateUnitNgonPointsFitToSquare(4, 0),
    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
      // use two fixed t values for the bezier curve approximation

      var t0 = 0.15;
      var t1 = 0.5;
      var t2 = 0.85;
      var bPts = this.generateBarrelBezierPts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);
      var approximateBarrelCurvePts = function approximateBarrelCurvePts(pts) {
        // approximate curve pts based on the two t values
        var m0 = qbezierPtAt({
          x: pts[0],
          y: pts[1]
        }, {
          x: pts[2],
          y: pts[3]
        }, {
          x: pts[4],
          y: pts[5]
        }, t0);
        var m1 = qbezierPtAt({
          x: pts[0],
          y: pts[1]
        }, {
          x: pts[2],
          y: pts[3]
        }, {
          x: pts[4],
          y: pts[5]
        }, t1);
        var m2 = qbezierPtAt({
          x: pts[0],
          y: pts[1]
        }, {
          x: pts[2],
          y: pts[3]
        }, {
          x: pts[4],
          y: pts[5]
        }, t2);
        return [pts[0], pts[1], m0.x, m0.y, m1.x, m1.y, m2.x, m2.y, pts[4], pts[5]];
      };
      var pts = [].concat(approximateBarrelCurvePts(bPts.topLeft), approximateBarrelCurvePts(bPts.topRight), approximateBarrelCurvePts(bPts.bottomRight), approximateBarrelCurvePts(bPts.bottomLeft));
      return polygonIntersectLine(x, y, pts, nodeX, nodeY);
    },
    generateBarrelBezierPts: function generateBarrelBezierPts(width, height, centerX, centerY) {
      var hh = height / 2;
      var hw = width / 2;
      var xBegin = centerX - hw;
      var xEnd = centerX + hw;
      var yBegin = centerY - hh;
      var yEnd = centerY + hh;
      var curveConstants = getBarrelCurveConstants(width, height);
      var hOffset = curveConstants.heightOffset;
      var wOffset = curveConstants.widthOffset;
      var ctrlPtXOffset = curveConstants.ctrlPtOffsetPct * width;

      // points are in clockwise order, inner (imaginary) control pt on [4, 5]
      var pts = {
        topLeft: [xBegin, yBegin + hOffset, xBegin + ctrlPtXOffset, yBegin, xBegin + wOffset, yBegin],
        topRight: [xEnd - wOffset, yBegin, xEnd - ctrlPtXOffset, yBegin, xEnd, yBegin + hOffset],
        bottomRight: [xEnd, yEnd - hOffset, xEnd - ctrlPtXOffset, yEnd, xEnd - wOffset, yEnd],
        bottomLeft: [xBegin + wOffset, yEnd, xBegin + ctrlPtXOffset, yEnd, xBegin, yEnd - hOffset]
      };
      pts.topLeft.isTop = true;
      pts.topRight.isTop = true;
      pts.bottomLeft.isBottom = true;
      pts.bottomRight.isBottom = true;
      return pts;
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
      var curveConstants = getBarrelCurveConstants(width, height);
      var hOffset = curveConstants.heightOffset;
      var wOffset = curveConstants.widthOffset;

      // Check hBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {
        return true;
      }

      // Check vBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {
        return true;
      }
      var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);
      var getCurveT = function getCurveT(x, y, curvePts) {
        var x0 = curvePts[4];
        var x1 = curvePts[2];
        var x2 = curvePts[0];
        var y0 = curvePts[5];
        // var y1 = curvePts[ 3 ];
        var y2 = curvePts[1];
        var xMin = Math.min(x0, x2);
        var xMax = Math.max(x0, x2);
        var yMin = Math.min(y0, y2);
        var yMax = Math.max(y0, y2);
        if (xMin <= x && x <= xMax && yMin <= y && y <= yMax) {
          var coeff = bezierPtsToQuadCoeff(x0, x1, x2);
          var roots = solveQuadratic(coeff[0], coeff[1], coeff[2], x);
          var validRoots = roots.filter(function (r) {
            return 0 <= r && r <= 1;
          });
          if (validRoots.length > 0) {
            return validRoots[0];
          }
        }
        return null;
      };
      var curveRegions = Object.keys(barrelCurvePts);
      for (var i = 0; i < curveRegions.length; i++) {
        var corner = curveRegions[i];
        var cornerPts = barrelCurvePts[corner];
        var t = getCurveT(x, y, cornerPts);
        if (t == null) {
          continue;
        }
        var y0 = cornerPts[5];
        var y1 = cornerPts[3];
        var y2 = cornerPts[1];
        var bezY = qbezierAt(y0, y1, y2, t);
        if (cornerPts.isTop && bezY <= y) {
          return true;
        }
        if (cornerPts.isBottom && y <= bezY) {
          return true;
        }
      }
      return false;
    }
  };
};
BRp$2.generateBottomRoundrectangle = function () {
  return this.nodeShapes['bottom-round-rectangle'] = this.nodeShapes['bottomroundrectangle'] = {
    renderer: this,
    name: 'bottom-round-rectangle',
    points: generateUnitNgonPointsFitToSquare(4, 0),
    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
    },
    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
      var topStartX = nodeX - (width / 2 + padding);
      var topStartY = nodeY - (height / 2 + padding);
      var topEndY = topStartY;
      var topEndX = nodeX + (width / 2 + padding);
      var topIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
      if (topIntersections.length > 0) {
        return topIntersections;
      }
      return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
    },
    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
      cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
      var diam = 2 * cornerRadius;

      // Check hBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
        return true;
      }

      // Check vBox
      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
        return true;
      }

      // check non-rounded top side
      var outerWidth = width / 2 + 2 * padding;
      var outerHeight = height / 2 + 2 * padding;
      var points = [centerX - outerWidth, centerY - outerHeight, centerX - outerWidth, centerY, centerX + outerWidth, centerY, centerX + outerWidth, centerY - outerHeight];
      if (pointInsidePolygonPoints(x, y, points)) {
        return true;
      }

      // Check bottom right quarter circle
      if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
        return true;
      }

      // Check bottom left quarter circle
      if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
        return true;
      }
      return false;
    }
  };
};
BRp$2.registerNodeShapes = function () {
  var nodeShapes = this.nodeShapes = {};
  var renderer = this;
  this.generateEllipse();
  this.generatePolygon('triangle', generateUnitNgonPointsFitToSquare(3, 0));
  this.generateRoundPolygon('round-triangle', generateUnitNgonPointsFitToSquare(3, 0));
  this.generatePolygon('rectangle', generateUnitNgonPointsFitToSquare(4, 0));
  nodeShapes['square'] = nodeShapes['rectangle'];
  this.generateRoundRectangle();
  this.generateCutRectangle();
  this.generateBarrel();
  this.generateBottomRoundrectangle();
  {
    var diamondPoints = [0, 1, 1, 0, 0, -1, -1, 0];
    this.generatePolygon('diamond', diamondPoints);
    this.generateRoundPolygon('round-diamond', diamondPoints);
  }
  this.generatePolygon('pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  this.generateRoundPolygon('round-pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  this.generatePolygon('hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  this.generateRoundPolygon('round-hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  this.generatePolygon('heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  this.generateRoundPolygon('round-heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  this.generatePolygon('octagon', generateUnitNgonPointsFitToSquare(8, 0));
  this.generateRoundPolygon('round-octagon', generateUnitNgonPointsFitToSquare(8, 0));
  var star5Points = new Array(20);
  {
    var outerPoints = generateUnitNgonPoints(5, 0);
    var innerPoints = generateUnitNgonPoints(5, Math.PI / 5);

    // Outer radius is 1; inner radius of star is smaller
    var innerRadius = 0.5 * (3 - Math.sqrt(5));
    innerRadius *= 1.57;
    for (var i = 0; i < innerPoints.length / 2; i++) {
      innerPoints[i * 2] *= innerRadius;
      innerPoints[i * 2 + 1] *= innerRadius;
    }
    for (var i = 0; i < 20 / 4; i++) {
      star5Points[i * 4] = outerPoints[i * 2];
      star5Points[i * 4 + 1] = outerPoints[i * 2 + 1];
      star5Points[i * 4 + 2] = innerPoints[i * 2];
      star5Points[i * 4 + 3] = innerPoints[i * 2 + 1];
    }
  }
  star5Points = fitPolygonToSquare(star5Points);
  this.generatePolygon('star', star5Points);
  this.generatePolygon('vee', [-1, -1, 0, -0.333, 1, -1, 0, 1]);
  this.generatePolygon('rhomboid', [-1, -1, 0.333, -1, 1, 1, -0.333, 1]);
  this.generatePolygon('right-rhomboid', [-0.333, -1, 1, -1, 0.333, 1, -1, 1]);
  this.nodeShapes['concavehexagon'] = this.generatePolygon('concave-hexagon', [-1, -0.95, -0.75, 0, -1, 0.95, 1, 0.95, 0.75, 0, 1, -0.95]);
  {
    var tagPoints = [-1, -1, 0.25, -1, 1, 0, 0.25, 1, -1, 1];
    this.generatePolygon('tag', tagPoints);
    this.generateRoundPolygon('round-tag', tagPoints);
  }
  nodeShapes.makePolygon = function (points) {
    // use caching on user-specified polygons so they are as fast as native shapes

    var key = points.join('$');
    var name = 'polygon-' + key;
    var shape;
    if (shape = this[name]) {
      // got cached shape
      return shape;
    }

    // create and cache new shape
    return renderer.generatePolygon(name, points);
  };
};

var BRp$1 = {};
BRp$1.timeToRender = function () {
  return this.redrawTotalTime / this.redrawCount;
};
BRp$1.redraw = function (options) {
  options = options || staticEmptyObject();
  var r = this;
  if (r.averageRedrawTime === undefined) {
    r.averageRedrawTime = 0;
  }
  if (r.lastRedrawTime === undefined) {
    r.lastRedrawTime = 0;
  }
  if (r.lastDrawTime === undefined) {
    r.lastDrawTime = 0;
  }
  r.requestedFrame = true;
  r.renderOptions = options;
};
BRp$1.beforeRender = function (fn, priority) {
  // the renderer can't add tick callbacks when destroyed
  if (this.destroyed) {
    return;
  }
  if (priority == null) {
    error('Priority is not optional for beforeRender');
  }
  var cbs = this.beforeRenderCallbacks;
  cbs.push({
    fn: fn,
    priority: priority
  });

  // higher priority callbacks executed first
  cbs.sort(function (a, b) {
    return b.priority - a.priority;
  });
};
var beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {
  var cbs = r.beforeRenderCallbacks;
  for (var i = 0; i < cbs.length; i++) {
    cbs[i].fn(willDraw, startTime);
  }
};
BRp$1.startRenderLoop = function () {
  var r = this;
  var cy = r.cy;
  if (r.renderLoopStarted) {
    return;
  } else {
    r.renderLoopStarted = true;
  }
  var _renderFn = function renderFn(requestTime) {
    if (r.destroyed) {
      return;
    }
    if (cy.batching()) ; else if (r.requestedFrame && !r.skipFrame) {
      beforeRenderCallbacks(r, true, requestTime);
      var startTime = performanceNow();
      r.render(r.renderOptions);
      var endTime = r.lastDrawTime = performanceNow();
      if (r.averageRedrawTime === undefined) {
        r.averageRedrawTime = endTime - startTime;
      }
      if (r.redrawCount === undefined) {
        r.redrawCount = 0;
      }
      r.redrawCount++;
      if (r.redrawTotalTime === undefined) {
        r.redrawTotalTime = 0;
      }
      var duration = endTime - startTime;
      r.redrawTotalTime += duration;
      r.lastRedrawTime = duration;

      // use a weighted average with a bias from the previous average so we don't spike so easily
      r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;
      r.requestedFrame = false;
    } else {
      beforeRenderCallbacks(r, false, requestTime);
    }
    r.skipFrame = false;
    requestAnimationFrame(_renderFn);
  };
  requestAnimationFrame(_renderFn);
};

var BaseRenderer = function BaseRenderer(options) {
  this.init(options);
};
var BR = BaseRenderer;
var BRp = BR.prototype;
BRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];
BRp.init = function (options) {
  var r = this;
  r.options = options;
  r.cy = options.cy;
  var ctr = r.container = options.cy.container();
  var containerWindow = r.cy.window();

  // prepend a stylesheet in the head such that
  if (containerWindow) {
    var document = containerWindow.document;
    var head = document.head;
    var stylesheetId = '__________cytoscape_stylesheet';
    var className = '__________cytoscape_container';
    var stylesheetAlreadyExists = document.getElementById(stylesheetId) != null;
    if (ctr.className.indexOf(className) < 0) {
      ctr.className = (ctr.className || '') + ' ' + className;
    }
    if (!stylesheetAlreadyExists) {
      var stylesheet = document.createElement('style');
      stylesheet.id = stylesheetId;
      stylesheet.textContent = '.' + className + ' { position: relative; }';
      head.insertBefore(stylesheet, head.children[0]); // first so lowest priority
    }
    var computedStyle = containerWindow.getComputedStyle(ctr);
    var position = computedStyle.getPropertyValue('position');
    if (position === 'static') {
      warn('A Cytoscape container has style position:static and so can not use UI extensions properly');
    }
  }
  r.selection = [undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag

  r.bezierProjPcts = [0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95];

  //--Pointer-related data
  r.hoverData = {
    down: null,
    last: null,
    downTime: null,
    triggerMode: null,
    dragging: false,
    initialPan: [null, null],
    capture: false
  };
  r.dragData = {
    possibleDragElements: []
  };
  r.touchData = {
    start: null,
    capture: false,
    // These 3 fields related to tap, taphold events
    startPosition: [null, null, null, null, null, null],
    singleTouchStartTime: null,
    singleTouchMoved: true,
    now: [null, null, null, null, null, null],
    earlier: [null, null, null, null, null, null]
  };
  r.redraws = 0;
  r.showFps = options.showFps;
  r.debug = options.debug;
  r.webgl = options.webgl;
  r.hideEdgesOnViewport = options.hideEdgesOnViewport;
  r.textureOnViewport = options.textureOnViewport;
  r.wheelSensitivity = options.wheelSensitivity;
  r.motionBlurEnabled = options.motionBlur; // on by default
  r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;
  r.motionBlur = options.motionBlur; // for initial kick off
  r.motionBlurOpacity = options.motionBlurOpacity;
  r.motionBlurTransparency = 1 - r.motionBlurOpacity;
  r.motionBlurPxRatio = 1;
  r.mbPxRBlurry = 1; //0.8;
  r.minMbLowQualFrames = 4;
  r.fullQualityMb = false;
  r.clearedForMotionBlur = [];
  r.desktopTapThreshold = options.desktopTapThreshold;
  r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;
  r.touchTapThreshold = options.touchTapThreshold;
  r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;
  r.tapholdDuration = 500;
  r.bindings = [];
  r.beforeRenderCallbacks = [];
  r.beforeRenderPriorities = {
    // higher priority execs before lower one
    animations: 400,
    eleCalcs: 300,
    eleTxrDeq: 200,
    lyrTxrDeq: 150,
    lyrTxrSkip: 100
  };
  r.registerNodeShapes();
  r.registerArrowShapes();
  r.registerCalculationListeners();
};
BRp.notify = function (eventName, eles) {
  var r = this;
  var cy = r.cy;

  // the renderer can't be notified after it's destroyed
  if (this.destroyed) {
    return;
  }
  if (eventName === 'init') {
    r.load();
    return;
  }
  if (eventName === 'destroy') {
    r.destroy();
    return;
  }
  if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {
    r.invalidateCachedZSortedEles();
  }
  if (eventName === 'viewport') {
    r.redrawHint('select', true);
  }
  if (eventName === 'gc') {
    r.redrawHint('gc', true);
  }
  if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {
    r.invalidateContainerClientCoordsCache();
    r.matchCanvasSize(r.container);
  }
  r.redrawHint('eles', true);
  r.redrawHint('drag', true);
  this.startRenderLoop();
  this.redraw();
};
BRp.destroy = function () {
  var r = this;
  r.destroyed = true;
  r.cy.stopAnimationLoop();
  for (var i = 0; i < r.bindings.length; i++) {
    var binding = r.bindings[i];
    var b = binding;
    var tgt = b.target;
    (tgt.off || tgt.removeEventListener).apply(tgt, b.args);
  }
  r.bindings = [];
  r.beforeRenderCallbacks = [];
  r.onUpdateEleCalcsFns = [];
  if (r.removeObserver) {
    r.removeObserver.disconnect();
  }
  if (r.styleObserver) {
    r.styleObserver.disconnect();
  }
  if (r.resizeObserver) {
    r.resizeObserver.disconnect();
  }
  if (r.labelCalcDiv) {
    try {
      document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef
    } catch (e) {
      // ie10 issue #1014
    }
  }
};
BRp.isHeadless = function () {
  return false;
};
[BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {
  extend(BRp, props);
});

var fullFpsTime = 1000 / 60; // assume 60 frames per second

var defs = {
  setupDequeueing: function setupDequeueing(opts) {
    return function setupDequeueingImpl() {
      var self = this;
      var r = this.renderer;
      if (self.dequeueingSetup) {
        return;
      } else {
        self.dequeueingSetup = true;
      }
      var queueRedraw = debounce(function () {
        r.redrawHint('eles', true);
        r.redrawHint('drag', true);
        r.redraw();
      }, opts.deqRedrawThreshold);
      var dequeue = function dequeue(willDraw, frameStartTime) {
        var startTime = performanceNow();
        var avgRenderTime = r.averageRedrawTime;
        var renderTime = r.lastRedrawTime;
        var deqd = [];
        var extent = r.cy.extent();
        var pixelRatio = r.getPixelRatio();

        // if we aren't in a tick that causes a draw, then the rendered style
        // queue won't automatically be flushed before dequeueing starts
        if (!willDraw) {
          r.flushRenderedStyleQueue();
        }
        while (true) {
          // eslint-disable-line no-constant-condition
          var now = performanceNow();
          var duration = now - startTime;
          var frameDuration = now - frameStartTime;
          if (renderTime < fullFpsTime) {
            // if we're rendering faster than the ideal fps, then do dequeueing
            // during all of the remaining frame time

            var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);
            if (frameDuration >= opts.deqFastCost * timeAvailable) {
              break;
            }
          } else {
            if (willDraw) {
              if (duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime) {
                break;
              }
            } else if (frameDuration >= opts.deqNoDrawCost * fullFpsTime) {
              break;
            }
          }
          var thisDeqd = opts.deq(self, pixelRatio, extent);
          if (thisDeqd.length > 0) {
            for (var i = 0; i < thisDeqd.length; i++) {
              deqd.push(thisDeqd[i]);
            }
          } else {
            break;
          }
        }

        // callbacks on dequeue
        if (deqd.length > 0) {
          opts.onDeqd(self, deqd);
          if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {
            queueRedraw();
          }
        }
      };
      var priority = opts.priority || noop$1;
      r.beforeRender(dequeue, priority(self));
    };
  }
};

// Allows lookups for (ele, lvl) => cache.
// Uses keys so elements may share the same cache.
var ElementTextureCacheLookup = /*#__PURE__*/function () {
  function ElementTextureCacheLookup(getKey) {
    var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;
    _classCallCheck(this, ElementTextureCacheLookup);
    this.idsByKey = new Map$1();
    this.keyForId = new Map$1();
    this.cachesByLvl = new Map$1();
    this.lvls = [];
    this.getKey = getKey;
    this.doesEleInvalidateKey = doesEleInvalidateKey;
  }
  return _createClass(ElementTextureCacheLookup, [{
    key: "getIdsFor",
    value: function getIdsFor(key) {
      if (key == null) {
        error("Can not get id list for null key");
      }
      var idsByKey = this.idsByKey;
      var ids = this.idsByKey.get(key);
      if (!ids) {
        ids = new Set$1();
        idsByKey.set(key, ids);
      }
      return ids;
    }
  }, {
    key: "addIdForKey",
    value: function addIdForKey(key, id) {
      if (key != null) {
        this.getIdsFor(key).add(id);
      }
    }
  }, {
    key: "deleteIdForKey",
    value: function deleteIdForKey(key, id) {
      if (key != null) {
        this.getIdsFor(key)["delete"](id);
      }
    }
  }, {
    key: "getNumberOfIdsForKey",
    value: function getNumberOfIdsForKey(key) {
      if (key == null) {
        return 0;
      } else {
        return this.getIdsFor(key).size;
      }
    }
  }, {
    key: "updateKeyMappingFor",
    value: function updateKeyMappingFor(ele) {
      var id = ele.id();
      var prevKey = this.keyForId.get(id);
      var currKey = this.getKey(ele);
      this.deleteIdForKey(prevKey, id);
      this.addIdForKey(currKey, id);
      this.keyForId.set(id, currKey);
    }
  }, {
    key: "deleteKeyMappingFor",
    value: function deleteKeyMappingFor(ele) {
      var id = ele.id();
      var prevKey = this.keyForId.get(id);
      this.deleteIdForKey(prevKey, id);
      this.keyForId["delete"](id);
    }
  }, {
    key: "keyHasChangedFor",
    value: function keyHasChangedFor(ele) {
      var id = ele.id();
      var prevKey = this.keyForId.get(id);
      var newKey = this.getKey(ele);
      return prevKey !== newKey;
    }
  }, {
    key: "isInvalid",
    value: function isInvalid(ele) {
      return this.keyHasChangedFor(ele) || this.doesEleInvalidateKey(ele);
    }
  }, {
    key: "getCachesAt",
    value: function getCachesAt(lvl) {
      var cachesByLvl = this.cachesByLvl,
        lvls = this.lvls;
      var caches = cachesByLvl.get(lvl);
      if (!caches) {
        caches = new Map$1();
        cachesByLvl.set(lvl, caches);
        lvls.push(lvl);
      }
      return caches;
    }
  }, {
    key: "getCache",
    value: function getCache(key, lvl) {
      return this.getCachesAt(lvl).get(key);
    }
  }, {
    key: "get",
    value: function get(ele, lvl) {
      var key = this.getKey(ele);
      var cache = this.getCache(key, lvl);

      // getting for an element may need to add to the id list b/c eles can share keys
      if (cache != null) {
        this.updateKeyMappingFor(ele);
      }
      return cache;
    }
  }, {
    key: "getForCachedKey",
    value: function getForCachedKey(ele, lvl) {
      var key = this.keyForId.get(ele.id()); // n.b. use cached key, not newly computed key
      var cache = this.getCache(key, lvl);
      return cache;
    }
  }, {
    key: "hasCache",
    value: function hasCache(key, lvl) {
      return this.getCachesAt(lvl).has(key);
    }
  }, {
    key: "has",
    value: function has(ele, lvl) {
      var key = this.getKey(ele);
      return this.hasCache(key, lvl);
    }
  }, {
    key: "setCache",
    value: function setCache(key, lvl, cache) {
      cache.key = key;
      this.getCachesAt(lvl).set(key, cache);
    }
  }, {
    key: "set",
    value: function set(ele, lvl, cache) {
      var key = this.getKey(ele);
      this.setCache(key, lvl, cache);
      this.updateKeyMappingFor(ele);
    }
  }, {
    key: "deleteCache",
    value: function deleteCache(key, lvl) {
      this.getCachesAt(lvl)["delete"](key);
    }
  }, {
    key: "delete",
    value: function _delete(ele, lvl) {
      var key = this.getKey(ele);
      this.deleteCache(key, lvl);
    }
  }, {
    key: "invalidateKey",
    value: function invalidateKey(key) {
      var _this = this;
      this.lvls.forEach(function (lvl) {
        return _this.deleteCache(key, lvl);
      });
    }

    // returns true if no other eles reference the invalidated cache (n.b. other eles may need the cache with the same key)
  }, {
    key: "invalidate",
    value: function invalidate(ele) {
      var id = ele.id();
      var key = this.keyForId.get(id); // n.b. use stored key rather than current (potential key)

      this.deleteKeyMappingFor(ele);
      var entireKeyInvalidated = this.doesEleInvalidateKey(ele);
      if (entireKeyInvalidated) {
        // clear mapping for current key
        this.invalidateKey(key);
      }
      return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;
    }
  }]);
}();

var minTxrH = 25; // the size of the texture cache for small height eles (special case)
var txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up
var minLvl$1 = -4; // when scaling smaller than that we don't need to re-render
var maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)
var maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used
var eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps
var defTxrWidth = 1024; // default/minimum texture width
var maxTxrW = 1024; // the maximum width of a texture
var maxTxrH = 1024; // the maximum height of a texture
var minUtility = 0.2; // if usage of texture is less than this, it is retired
var maxFullness = 0.8; // fullness of texture after which queue removal is checked
var maxFullnessChecks = 10; // dequeued after this many checks
var deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
var deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time
var deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
var deqFastCost$1 = 0.9; // % of frame time to be used when >60fps
var deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
var maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch

var getTxrReasons = {
  dequeue: 'dequeue',
  downscale: 'downscale',
  highQuality: 'highQuality'
};
var initDefaults = defaults$g({
  getKey: null,
  doesEleInvalidateKey: falsify,
  drawElement: null,
  getBoundingBox: null,
  getRotationPoint: null,
  getRotationOffset: null,
  isVisible: trueify,
  allowEdgeTxrCaching: true,
  allowParentTxrCaching: true
});
var ElementTextureCache = function ElementTextureCache(renderer, initOptions) {
  var self = this;
  self.renderer = renderer;
  self.onDequeues = [];
  var opts = initDefaults(initOptions);
  extend(self, opts);
  self.lookup = new ElementTextureCacheLookup(opts.getKey, opts.doesEleInvalidateKey);
  self.setupDequeueing();
};
var ETCp = ElementTextureCache.prototype;
ETCp.reasons = getTxrReasons;

// the list of textures in which new subtextures for elements can be placed
ETCp.getTextureQueue = function (txrH) {
  var self = this;
  self.eleImgCaches = self.eleImgCaches || {};
  return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];
};

// the list of usused textures which can be recycled (in use in texture queue)
ETCp.getRetiredTextureQueue = function (txrH) {
  var self = this;
  var rtxtrQs = self.eleImgCaches.retired = self.eleImgCaches.retired || {};
  var rtxtrQ = rtxtrQs[txrH] = rtxtrQs[txrH] || [];
  return rtxtrQ;
};

// queue of element draw requests at different scale levels
ETCp.getElementQueue = function () {
  var self = this;
  var q = self.eleCacheQueue = self.eleCacheQueue || new Heap(function (a, b) {
    return b.reqs - a.reqs;
  });
  return q;
};

// queue of element draw requests at different scale levels (element id lookup)
ETCp.getElementKeyToQueue = function () {
  var self = this;
  var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};
  return k2q;
};
ETCp.getElement = function (ele, bb, pxRatio, lvl, reason) {
  var self = this;
  var r = this.renderer;
  var zoom = r.cy.zoom();
  var lookup = this.lookup;
  if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {
    return null;
  }
  if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {
    return null;
  }
  if (lvl == null) {
    lvl = Math.ceil(log2(zoom * pxRatio));
  }
  if (lvl < minLvl$1) {
    lvl = minLvl$1;
  } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {
    return null;
  }
  var scale = Math.pow(2, lvl);
  var eleScaledH = bb.h * scale;
  var eleScaledW = bb.w * scale;
  var scaledLabelShown = r.eleTextBiggerThanMin(ele, scale);
  if (!this.isVisible(ele, scaledLabelShown)) {
    return null;
  }
  var eleCache = lookup.get(ele, lvl);

  // if this get was on an unused/invalidated cache, then restore the texture usage metric
  if (eleCache && eleCache.invalidated) {
    eleCache.invalidated = false;
    eleCache.texture.invalidatedWidth -= eleCache.width;
  }
  if (eleCache) {
    return eleCache;
  }
  var txrH; // which texture height this ele belongs to

  if (eleScaledH <= minTxrH) {
    txrH = minTxrH;
  } else if (eleScaledH <= txrStepH) {
    txrH = txrStepH;
  } else {
    txrH = Math.ceil(eleScaledH / txrStepH) * txrStepH;
  }
  if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {
    return null; // caching large elements is not efficient
  }
  var txrQ = self.getTextureQueue(txrH);

  // first try the second last one in case it has space at the end
  var txr = txrQ[txrQ.length - 2];
  var addNewTxr = function addNewTxr() {
    return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);
  };

  // try the last one if there is no second last one
  if (!txr) {
    txr = txrQ[txrQ.length - 1];
  }

  // if the last one doesn't exist, we need a first one
  if (!txr) {
    txr = addNewTxr();
  }

  // if there's no room in the current texture, we need a new one
  if (txr.width - txr.usedWidth < eleScaledW) {
    txr = addNewTxr();
  }
  var scalableFrom = function scalableFrom(otherCache) {
    return otherCache && otherCache.scaledLabelShown === scaledLabelShown;
  };
  var deqing = reason && reason === getTxrReasons.dequeue;
  var highQualityReq = reason && reason === getTxrReasons.highQuality;
  var downscaleReq = reason && reason === getTxrReasons.downscale;
  var higherCache; // the nearest cache with a higher level
  for (var l = lvl + 1; l <= maxLvl$1; l++) {
    var c = lookup.get(ele, l);
    if (c) {
      higherCache = c;
      break;
    }
  }
  var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;
  var downscale = function downscale() {
    txr.context.drawImage(oneUpCache.texture.canvas, oneUpCache.x, 0, oneUpCache.width, oneUpCache.height, txr.usedWidth, 0, eleScaledW, eleScaledH);
  };

  // reset ele area in texture
  txr.context.setTransform(1, 0, 0, 1, 0, 0);
  txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);
  if (scalableFrom(oneUpCache)) {
    // then we can relatively cheaply rescale the existing image w/o rerendering
    downscale();
  } else if (scalableFrom(higherCache)) {
    // then use the higher cache for now and queue the next level down
    // to cheaply scale towards the smaller level

    if (highQualityReq) {
      for (var _l = higherCache.level; _l > lvl; _l--) {
        oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);
      }
      downscale();
    } else {
      self.queueElement(ele, higherCache.level - 1);
      return higherCache;
    }
  } else {
    var lowerCache; // the nearest cache with a lower level
    if (!deqing && !highQualityReq && !downscaleReq) {
      for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {
        var _c = lookup.get(ele, _l2);
        if (_c) {
          lowerCache = _c;
          break;
        }
      }
    }
    if (scalableFrom(lowerCache)) {
      // then use the lower quality cache for now and queue the better one for later

      self.queueElement(ele, lvl);
      return lowerCache;
    }
    txr.context.translate(txr.usedWidth, 0);
    txr.context.scale(scale, scale);
    this.drawElement(txr.context, ele, bb, scaledLabelShown, false);
    txr.context.scale(1 / scale, 1 / scale);
    txr.context.translate(-txr.usedWidth, 0);
  }
  eleCache = {
    x: txr.usedWidth,
    texture: txr,
    level: lvl,
    scale: scale,
    width: eleScaledW,
    height: eleScaledH,
    scaledLabelShown: scaledLabelShown
  };
  txr.usedWidth += Math.ceil(eleScaledW + eleTxrSpacing);
  txr.eleCaches.push(eleCache);
  lookup.set(ele, lvl, eleCache);
  self.checkTextureFullness(txr);
  return eleCache;
};
ETCp.invalidateElements = function (eles) {
  for (var i = 0; i < eles.length; i++) {
    this.invalidateElement(eles[i]);
  }
};
ETCp.invalidateElement = function (ele) {
  var self = this;
  var lookup = self.lookup;
  var caches = [];
  var invalid = lookup.isInvalid(ele);
  if (!invalid) {
    return; // override the invalidation request if the element key has not changed
  }
  for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {
    var cache = lookup.getForCachedKey(ele, lvl);
    if (cache) {
      caches.push(cache);
    }
  }
  var noOtherElesUseCache = lookup.invalidate(ele);
  if (noOtherElesUseCache) {
    for (var i = 0; i < caches.length; i++) {
      var _cache = caches[i];
      var txr = _cache.texture;

      // remove space from the texture it belongs to
      txr.invalidatedWidth += _cache.width;

      // mark the cache as invalidated
      _cache.invalidated = true;

      // retire the texture if its utility is low
      self.checkTextureUtility(txr);
    }
  }

  // remove from queue since the old req was for the old state
  self.removeFromQueue(ele);
};
ETCp.checkTextureUtility = function (txr) {
  // invalidate all entries in the cache if the cache size is small
  if (txr.invalidatedWidth >= minUtility * txr.width) {
    this.retireTexture(txr);
  }
};
ETCp.checkTextureFullness = function (txr) {
  // if texture has been mostly filled and passed over several times, remove
  // it from the queue so we don't need to waste time looking at it to put new things

  var self = this;
  var txrQ = self.getTextureQueue(txr.height);
  if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {
    removeFromArray(txrQ, txr);
  } else {
    txr.fullnessChecks++;
  }
};
ETCp.retireTexture = function (txr) {
  var self = this;
  var txrH = txr.height;
  var txrQ = self.getTextureQueue(txrH);
  var lookup = this.lookup;

  // retire the texture from the active / searchable queue:

  removeFromArray(txrQ, txr);
  txr.retired = true;

  // remove the refs from the eles to the caches:

  var eleCaches = txr.eleCaches;
  for (var i = 0; i < eleCaches.length; i++) {
    var eleCache = eleCaches[i];
    lookup.deleteCache(eleCache.key, eleCache.level);
  }
  clearArray(eleCaches);

  // add the texture to a retired queue so it can be recycled in future:

  var rtxtrQ = self.getRetiredTextureQueue(txrH);
  rtxtrQ.push(txr);
};
ETCp.addTexture = function (txrH, minW) {
  var self = this;
  var txrQ = self.getTextureQueue(txrH);
  var txr = {};
  txrQ.push(txr);
  txr.eleCaches = [];
  txr.height = txrH;
  txr.width = Math.max(defTxrWidth, minW);
  txr.usedWidth = 0;
  txr.invalidatedWidth = 0;
  txr.fullnessChecks = 0;
  txr.canvas = self.renderer.makeOffscreenCanvas(txr.width, txr.height);
  txr.context = txr.canvas.getContext('2d');
  return txr;
};
ETCp.recycleTexture = function (txrH, minW) {
  var self = this;
  var txrQ = self.getTextureQueue(txrH);
  var rtxtrQ = self.getRetiredTextureQueue(txrH);
  for (var i = 0; i < rtxtrQ.length; i++) {
    var txr = rtxtrQ[i];
    if (txr.width >= minW) {
      txr.retired = false;
      txr.usedWidth = 0;
      txr.invalidatedWidth = 0;
      txr.fullnessChecks = 0;
      clearArray(txr.eleCaches);
      txr.context.setTransform(1, 0, 0, 1, 0, 0);
      txr.context.clearRect(0, 0, txr.width, txr.height);
      removeFromArray(rtxtrQ, txr);
      txrQ.push(txr);
      return txr;
    }
  }
};
ETCp.queueElement = function (ele, lvl) {
  var self = this;
  var q = self.getElementQueue();
  var k2q = self.getElementKeyToQueue();
  var key = this.getKey(ele);
  var existingReq = k2q[key];
  if (existingReq) {
    // use the max lvl b/c in between lvls are cheap to make
    existingReq.level = Math.max(existingReq.level, lvl);
    existingReq.eles.merge(ele);
    existingReq.reqs++;
    q.updateItem(existingReq);
  } else {
    var req = {
      eles: ele.spawn().merge(ele),
      level: lvl,
      reqs: 1,
      key: key
    };
    q.push(req);
    k2q[key] = req;
  }
};
ETCp.dequeue = function (pxRatio /*, extent*/) {
  var self = this;
  var q = self.getElementQueue();
  var k2q = self.getElementKeyToQueue();
  var dequeued = [];
  var lookup = self.lookup;
  for (var i = 0; i < maxDeqSize$1; i++) {
    if (q.size() > 0) {
      var req = q.pop();
      var key = req.key;
      var ele = req.eles[0]; // all eles have the same key
      var cacheExists = lookup.hasCache(ele, req.level);

      // clear out the key to req lookup
      k2q[key] = null;

      // dequeueing isn't necessary with an existing cache
      if (cacheExists) {
        continue;
      }
      dequeued.push(req);
      var bb = self.getBoundingBox(ele);
      self.getElement(ele, bb, pxRatio, req.level, getTxrReasons.dequeue);
    } else {
      break;
    }
  }
  return dequeued;
};
ETCp.removeFromQueue = function (ele) {
  var self = this;
  var q = self.getElementQueue();
  var k2q = self.getElementKeyToQueue();
  var key = this.getKey(ele);
  var req = k2q[key];
  if (req != null) {
    if (req.eles.length === 1) {
      // remove if last ele in the req
      // bring to front of queue
      req.reqs = MAX_INT$1;
      q.updateItem(req);
      q.pop(); // remove from queue

      k2q[key] = null; // remove from lookup map
    } else {
      // otherwise just remove ele from req
      req.eles.unmerge(ele);
    }
  }
};
ETCp.onDequeue = function (fn) {
  this.onDequeues.push(fn);
};
ETCp.offDequeue = function (fn) {
  removeFromArray(this.onDequeues, fn);
};
ETCp.setupDequeueing = defs.setupDequeueing({
  deqRedrawThreshold: deqRedrawThreshold$1,
  deqCost: deqCost$1,
  deqAvgCost: deqAvgCost$1,
  deqNoDrawCost: deqNoDrawCost$1,
  deqFastCost: deqFastCost$1,
  deq: function deq(self, pxRatio, extent) {
    return self.dequeue(pxRatio, extent);
  },
  onDeqd: function onDeqd(self, deqd) {
    for (var i = 0; i < self.onDequeues.length; i++) {
      var fn = self.onDequeues[i];
      fn(deqd);
    }
  },
  shouldRedraw: function shouldRedraw(self, deqd, pxRatio, extent) {
    for (var i = 0; i < deqd.length; i++) {
      var eles = deqd[i].eles;
      for (var j = 0; j < eles.length; j++) {
        var bb = eles[j].boundingBox();
        if (boundingBoxesIntersect(bb, extent)) {
          return true;
        }
      }
    }
    return false;
  },
  priority: function priority(self) {
    return self.renderer.beforeRenderPriorities.eleTxrDeq;
  }
});

var defNumLayers = 1; // default number of layers to use
var minLvl = -4; // when scaling smaller than that we don't need to re-render
var maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)
var maxZoom = 3.99; // beyond this zoom level, layered textures are not used
var deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
var refineEleDebounceTime = 50; // time to debounce sharper ele texture updates
var deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
var deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time
var deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
var deqFastCost = 0.9; // % of frame time to be used when >60fps
var maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch
var invalidThreshold = 250; // time threshold for disabling b/c of invalidations
var maxLayerArea = 4000 * 4000; // layers can't be bigger than this
var maxLayerDim = 32767; // maximum size for the width/height of layer canvases
var useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)

// var log = function(){ console.log.apply( console, arguments ); };

var LayeredTextureCache = function LayeredTextureCache(renderer) {
  var self = this;
  var r = self.renderer = renderer;
  var cy = r.cy;
  self.layersByLevel = {}; // e.g. 2 => [ layer1, layer2, ..., layerN ]

  self.firstGet = true;
  self.lastInvalidationTime = performanceNow() - 2 * invalidThreshold;
  self.skipping = false;
  self.eleTxrDeqs = cy.collection();
  self.scheduleElementRefinement = debounce(function () {
    self.refineElementTextures(self.eleTxrDeqs);
    self.eleTxrDeqs.unmerge(self.eleTxrDeqs);
  }, refineEleDebounceTime);
  r.beforeRender(function (willDraw, now) {
    if (now - self.lastInvalidationTime <= invalidThreshold) {
      self.skipping = true;
    } else {
      self.skipping = false;
    }
  }, r.beforeRenderPriorities.lyrTxrSkip);
  var qSort = function qSort(a, b) {
    return b.reqs - a.reqs;
  };
  self.layersQueue = new Heap(qSort);
  self.setupDequeueing();
};
var LTCp = LayeredTextureCache.prototype;
var layerIdPool = 0;
var MAX_INT = Math.pow(2, 53) - 1;
LTCp.makeLayer = function (bb, lvl) {
  var scale = Math.pow(2, lvl);
  var w = Math.ceil(bb.w * scale);
  var h = Math.ceil(bb.h * scale);
  var canvas = this.renderer.makeOffscreenCanvas(w, h);
  var layer = {
    id: layerIdPool = ++layerIdPool % MAX_INT,
    bb: bb,
    level: lvl,
    width: w,
    height: h,
    canvas: canvas,
    context: canvas.getContext('2d'),
    eles: [],
    elesQueue: [],
    reqs: 0
  };

  // log('make layer %s with w %s and h %s and lvl %s', layer.id, layer.width, layer.height, layer.level);

  var cxt = layer.context;
  var dx = -layer.bb.x1;
  var dy = -layer.bb.y1;

  // do the transform on creation to save cycles (it's the same for all eles)
  cxt.scale(scale, scale);
  cxt.translate(dx, dy);
  return layer;
};
LTCp.getLayers = function (eles, pxRatio, lvl) {
  var self = this;
  var r = self.renderer;
  var cy = r.cy;
  var zoom = cy.zoom();
  var firstGet = self.firstGet;
  self.firstGet = false;

  // log('--\nget layers with %s eles', eles.length);
  //log eles.map(function(ele){ return ele.id() }) );

  if (lvl == null) {
    lvl = Math.ceil(log2(zoom * pxRatio));
    if (lvl < minLvl) {
      lvl = minLvl;
    } else if (zoom >= maxZoom || lvl > maxLvl) {
      return null;
    }
  }
  self.validateLayersElesOrdering(lvl, eles);
  var layersByLvl = self.layersByLevel;
  var scale = Math.pow(2, lvl);
  var layers = layersByLvl[lvl] = layersByLvl[lvl] || [];
  var bb;
  var lvlComplete = self.levelIsComplete(lvl, eles);
  var tmpLayers;
  var checkTempLevels = function checkTempLevels() {
    var canUseAsTmpLvl = function canUseAsTmpLvl(l) {
      self.validateLayersElesOrdering(l, eles);
      if (self.levelIsComplete(l, eles)) {
        tmpLayers = layersByLvl[l];
        return true;
      }
    };
    var checkLvls = function checkLvls(dir) {
      if (tmpLayers) {
        return;
      }
      for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {
        if (canUseAsTmpLvl(l)) {
          break;
        }
      }
    };
    checkLvls(1);
    checkLvls(-1);

    // remove the invalid layers; they will be replaced as needed later in this function
    for (var i = layers.length - 1; i >= 0; i--) {
      var layer = layers[i];
      if (layer.invalid) {
        removeFromArray(layers, layer);
      }
    }
  };
  if (!lvlComplete) {
    // if the current level is incomplete, then use the closest, best quality layerset temporarily
    // and later queue the current layerset so we can get the proper quality level soon

    checkTempLevels();
  } else {
    // log('level complete, using existing layers\n--');
    return layers;
  }
  var getBb = function getBb() {
    if (!bb) {
      bb = makeBoundingBox();
      for (var i = 0; i < eles.length; i++) {
        updateBoundingBox(bb, eles[i].boundingBox());
      }
    }
    return bb;
  };
  var makeLayer = function makeLayer(opts) {
    opts = opts || {};
    var after = opts.after;
    getBb();
    var w = Math.ceil(bb.w * scale);
    var h = Math.ceil(bb.h * scale);
    if (w > maxLayerDim || h > maxLayerDim) {
      return null;
    }
    var area = w * h;
    if (area > maxLayerArea) {
      return null;
    }
    var layer = self.makeLayer(bb, lvl);
    if (after != null) {
      var index = layers.indexOf(after) + 1;
      layers.splice(index, 0, layer);
    } else if (opts.insert === undefined || opts.insert) {
      // no after specified => first layer made so put at start
      layers.unshift(layer);
    }

    // if( tmpLayers ){
    //self.queueLayer( layer );
    // }

    return layer;
  };
  if (self.skipping && !firstGet) {
    // log('skip layers');
    return null;
  }

  // log('do layers');

  var layer = null;
  var maxElesPerLayer = eles.length / defNumLayers;
  var allowLazyQueueing = !firstGet;
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    var rs = ele._private.rscratch;
    var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};

    // log('look at ele', ele.id());

    var existingLayer = caches[lvl];
    if (existingLayer) {
      // reuse layer for later eles
      // log('reuse layer for', ele.id());
      layer = existingLayer;
      continue;
    }
    if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {
      // log('make new layer for ele %s', ele.id());

      layer = makeLayer({
        insert: true,
        after: layer
      });

      // if now layer can be built then we can't use layers at this level
      if (!layer) {
        return null;
      }

      // log('new layer with id %s', layer.id);
    }
    if (tmpLayers || allowLazyQueueing) {
      // log('queue ele %s in layer %s', ele.id(), layer.id);
      self.queueLayer(layer, ele);
    } else {
      // log('draw ele %s in layer %s', ele.id(), layer.id);
      self.drawEleInLayer(layer, ele, lvl, pxRatio);
    }
    layer.eles.push(ele);
    caches[lvl] = layer;
  }

  // log('--');

  if (tmpLayers) {
    // then we only queued the current layerset and can't draw it yet
    return tmpLayers;
  }
  if (allowLazyQueueing) {
    // log('lazy queue level', lvl);
    return null;
  }
  return layers;
};

// a layer may want to use an ele cache of a higher level to avoid blurriness
// so the layer level might not equal the ele level
LTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {
  return lvl;
};
LTCp.drawEleInLayer = function (layer, ele, lvl, pxRatio) {
  var self = this;
  var r = this.renderer;
  var context = layer.context;
  var bb = ele.boundingBox();
  if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
    return;
  }
  lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);
  {
    r.setImgSmoothing(context, false);
  }
  {
    r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);
  }
  {
    r.setImgSmoothing(context, true);
  }
};
LTCp.levelIsComplete = function (lvl, eles) {
  var self = this;
  var layers = self.layersByLevel[lvl];
  if (!layers || layers.length === 0) {
    return false;
  }
  var numElesInLayers = 0;
  for (var i = 0; i < layers.length; i++) {
    var layer = layers[i];

    // if there are any eles needed to be drawn yet, the level is not complete
    if (layer.reqs > 0) {
      return false;
    }

    // if the layer is invalid, the level is not complete
    if (layer.invalid) {
      return false;
    }
    numElesInLayers += layer.eles.length;
  }

  // we should have exactly the number of eles passed in to be complete
  if (numElesInLayers !== eles.length) {
    return false;
  }
  return true;
};
LTCp.validateLayersElesOrdering = function (lvl, eles) {
  var layers = this.layersByLevel[lvl];
  if (!layers) {
    return;
  }

  // if in a layer the eles are not in the same order, then the layer is invalid
  // (i.e. there is an ele in between the eles in the layer)

  for (var i = 0; i < layers.length; i++) {
    var layer = layers[i];
    var offset = -1;

    // find the offset
    for (var j = 0; j < eles.length; j++) {
      if (layer.eles[0] === eles[j]) {
        offset = j;
        break;
      }
    }
    if (offset < 0) {
      // then the layer has nonexistent elements and is invalid
      this.invalidateLayer(layer);
      continue;
    }

    // the eles in the layer must be in the same continuous order, else the layer is invalid

    var o = offset;
    for (var j = 0; j < layer.eles.length; j++) {
      if (layer.eles[j] !== eles[o + j]) {
        // log('invalidate based on ordering', layer.id);

        this.invalidateLayer(layer);
        break;
      }
    }
  }
};
LTCp.updateElementsInLayers = function (eles, update) {
  var self = this;
  var isEles = element(eles[0]);

  // collect udpated elements (cascaded from the layers) and update each
  // layer itself along the way
  for (var i = 0; i < eles.length; i++) {
    var req = isEles ? null : eles[i];
    var ele = isEles ? eles[i] : eles[i].ele;
    var rs = ele._private.rscratch;
    var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
    for (var l = minLvl; l <= maxLvl; l++) {
      var layer = caches[l];
      if (!layer) {
        continue;
      }

      // if update is a request from the ele cache, then it affects only
      // the matching level
      if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {
        continue;
      }
      update(layer, ele, req);
    }
  }
};
LTCp.haveLayers = function () {
  var self = this;
  var haveLayers = false;
  for (var l = minLvl; l <= maxLvl; l++) {
    var layers = self.layersByLevel[l];
    if (layers && layers.length > 0) {
      haveLayers = true;
      break;
    }
  }
  return haveLayers;
};
LTCp.invalidateElements = function (eles) {
  var self = this;
  if (eles.length === 0) {
    return;
  }
  self.lastInvalidationTime = performanceNow();

  // log('update invalidate layer time from eles');

  if (eles.length === 0 || !self.haveLayers()) {
    return;
  }
  self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {
    self.invalidateLayer(layer);
  });
};
LTCp.invalidateLayer = function (layer) {
  // log('update invalidate layer time');

  this.lastInvalidationTime = performanceNow();
  if (layer.invalid) {
    return;
  } // save cycles

  var lvl = layer.level;
  var eles = layer.eles;
  var layers = this.layersByLevel[lvl];

  // log('invalidate layer', layer.id );

  removeFromArray(layers, layer);
  // layer.eles = [];

  layer.elesQueue = [];
  layer.invalid = true;
  if (layer.replacement) {
    layer.replacement.invalid = true;
  }
  for (var i = 0; i < eles.length; i++) {
    var caches = eles[i]._private.rscratch.imgLayerCaches;
    if (caches) {
      caches[lvl] = null;
    }
  }
};
LTCp.refineElementTextures = function (eles) {
  var self = this;

  // log('refine', eles.length);

  self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {
    var rLyr = layer.replacement;
    if (!rLyr) {
      rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);
      rLyr.replaces = layer;
      rLyr.eles = layer.eles;

      // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);
    }
    if (!rLyr.reqs) {
      for (var i = 0; i < rLyr.eles.length; i++) {
        self.queueLayer(rLyr, rLyr.eles[i]);
      }

      // log('queue replacement layer refinement', rLyr.id);
    }
  });
};
LTCp.enqueueElementRefinement = function (ele) {
  this.eleTxrDeqs.merge(ele);
  this.scheduleElementRefinement();
};
LTCp.queueLayer = function (layer, ele) {
  var self = this;
  var q = self.layersQueue;
  var elesQ = layer.elesQueue;
  var hasId = elesQ.hasId = elesQ.hasId || {};

  // if a layer is going to be replaced, queuing is a waste of time
  if (layer.replacement) {
    return;
  }
  if (ele) {
    if (hasId[ele.id()]) {
      return;
    }
    elesQ.push(ele);
    hasId[ele.id()] = true;
  }
  if (layer.reqs) {
    layer.reqs++;
    q.updateItem(layer);
  } else {
    layer.reqs = 1;
    q.push(layer);
  }
};
LTCp.dequeue = function (pxRatio) {
  var self = this;
  var q = self.layersQueue;
  var deqd = [];
  var eleDeqs = 0;
  while (eleDeqs < maxDeqSize) {
    if (q.size() === 0) {
      break;
    }
    var layer = q.peek();

    // if a layer has been or will be replaced, then don't waste time with it
    if (layer.replacement) {
      // log('layer %s in queue skipped b/c it already has a replacement', layer.id);
      q.pop();
      continue;
    }

    // if this is a replacement layer that has been superceded, then forget it
    if (layer.replaces && layer !== layer.replaces.replacement) {
      // log('layer is no longer the most uptodate replacement; dequeued', layer.id)
      q.pop();
      continue;
    }
    if (layer.invalid) {
      // log('replacement layer %s is invalid; dequeued', layer.id);
      q.pop();
      continue;
    }
    var ele = layer.elesQueue.shift();
    if (ele) {
      // log('dequeue layer %s', layer.id);

      self.drawEleInLayer(layer, ele, layer.level, pxRatio);
      eleDeqs++;
    }
    if (deqd.length === 0) {
      // we need only one entry in deqd to queue redrawing etc
      deqd.push(true);
    }

    // if the layer has all its eles done, then remove from the queue
    if (layer.elesQueue.length === 0) {
      q.pop();
      layer.reqs = 0;

      // log('dequeue of layer %s complete', layer.id);

      // when a replacement layer is dequeued, it replaces the old layer in the level
      if (layer.replaces) {
        self.applyLayerReplacement(layer);
      }
      self.requestRedraw();
    }
  }
  return deqd;
};
LTCp.applyLayerReplacement = function (layer) {
  var self = this;
  var layersInLevel = self.layersByLevel[layer.level];
  var replaced = layer.replaces;
  var index = layersInLevel.indexOf(replaced);

  // if the replaced layer is not in the active list for the level, then replacing
  // refs would be a mistake (i.e. overwriting the true active layer)
  if (index < 0 || replaced.invalid) {
    // log('replacement layer would have no effect', layer.id);
    return;
  }
  layersInLevel[index] = layer; // replace level ref

  // replace refs in eles
  for (var i = 0; i < layer.eles.length; i++) {
    var _p = layer.eles[i]._private;
    var cache = _p.imgLayerCaches = _p.imgLayerCaches || {};
    if (cache) {
      cache[layer.level] = layer;
    }
  }

  // log('apply replacement layer %s over %s', layer.id, replaced.id);

  self.requestRedraw();
};
LTCp.requestRedraw = debounce(function () {
  var r = this.renderer;
  r.redrawHint('eles', true);
  r.redrawHint('drag', true);
  r.redraw();
}, 100);
LTCp.setupDequeueing = defs.setupDequeueing({
  deqRedrawThreshold: deqRedrawThreshold,
  deqCost: deqCost,
  deqAvgCost: deqAvgCost,
  deqNoDrawCost: deqNoDrawCost,
  deqFastCost: deqFastCost,
  deq: function deq(self, pxRatio) {
    return self.dequeue(pxRatio);
  },
  onDeqd: noop$1,
  shouldRedraw: trueify,
  priority: function priority(self) {
    return self.renderer.beforeRenderPriorities.lyrTxrDeq;
  }
});

var CRp$b = {};
var impl;
function polygon(context, points) {
  for (var i = 0; i < points.length; i++) {
    var pt = points[i];
    context.lineTo(pt.x, pt.y);
  }
}
function triangleBackcurve(context, points, controlPoint) {
  var firstPt;
  for (var i = 0; i < points.length; i++) {
    var pt = points[i];
    if (i === 0) {
      firstPt = pt;
    }
    context.lineTo(pt.x, pt.y);
  }
  context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);
}
function triangleTee(context, trianglePoints, teePoints) {
  if (context.beginPath) {
    context.beginPath();
  }
  var triPts = trianglePoints;
  for (var i = 0; i < triPts.length; i++) {
    var pt = triPts[i];
    context.lineTo(pt.x, pt.y);
  }
  var teePts = teePoints;
  var firstTeePt = teePoints[0];
  context.moveTo(firstTeePt.x, firstTeePt.y);
  for (var i = 1; i < teePts.length; i++) {
    var pt = teePts[i];
    context.lineTo(pt.x, pt.y);
  }
  if (context.closePath) {
    context.closePath();
  }
}
function circleTriangle(context, trianglePoints, rx, ry, r) {
  if (context.beginPath) {
    context.beginPath();
  }
  context.arc(rx, ry, r, 0, Math.PI * 2, false);
  var triPts = trianglePoints;
  var firstTrPt = triPts[0];
  context.moveTo(firstTrPt.x, firstTrPt.y);
  for (var i = 0; i < triPts.length; i++) {
    var pt = triPts[i];
    context.lineTo(pt.x, pt.y);
  }
  if (context.closePath) {
    context.closePath();
  }
}
function circle$1(context, rx, ry, r) {
  context.arc(rx, ry, r, 0, Math.PI * 2, false);
}
CRp$b.arrowShapeImpl = function (name) {
  return (impl || (impl = {
    'polygon': polygon,
    'triangle-backcurve': triangleBackcurve,
    'triangle-tee': triangleTee,
    'circle-triangle': circleTriangle,
    'triangle-cross': triangleTee,
    'circle': circle$1
  }))[name];
};

var CRp$a = {};
CRp$a.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {
  var r = this;
  if (ele.isNode()) {
    r.drawNode(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  } else {
    r.drawEdge(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  }
};
CRp$a.drawElementOverlay = function (context, ele) {
  var r = this;
  if (ele.isNode()) {
    r.drawNodeOverlay(context, ele);
  } else {
    r.drawEdgeOverlay(context, ele);
  }
};
CRp$a.drawElementUnderlay = function (context, ele) {
  var r = this;
  if (ele.isNode()) {
    r.drawNodeUnderlay(context, ele);
  } else {
    r.drawEdgeUnderlay(context, ele);
  }
};
CRp$a.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {
  var r = this;
  var bb = eleTxrCache.getBoundingBox(ele);
  if (bb.w === 0 || bb.h === 0) {
    return;
  } // ignore zero size case

  var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);
  if (eleCache != null) {
    var opacity = getOpacity(r, ele);
    if (opacity === 0) {
      return;
    }
    var theta = getRotation(r, ele);
    var x1 = bb.x1,
      y1 = bb.y1,
      w = bb.w,
      h = bb.h;
    var x, y, sx, sy, smooth;
    if (theta !== 0) {
      var rotPt = eleTxrCache.getRotationPoint(ele);
      sx = rotPt.x;
      sy = rotPt.y;
      context.translate(sx, sy);
      context.rotate(theta);
      smooth = r.getImgSmoothing(context);
      if (!smooth) {
        r.setImgSmoothing(context, true);
      }
      var off = eleTxrCache.getRotationOffset(ele);
      x = off.x;
      y = off.y;
    } else {
      x = x1;
      y = y1;
    }
    var oldGlobalAlpha;
    if (opacity !== 1) {
      oldGlobalAlpha = context.globalAlpha;
      context.globalAlpha = oldGlobalAlpha * opacity;
    }
    context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);
    if (opacity !== 1) {
      context.globalAlpha = oldGlobalAlpha;
    }
    if (theta !== 0) {
      context.rotate(-theta);
      context.translate(-sx, -sy);
      if (!smooth) {
        r.setImgSmoothing(context, false);
      }
    }
  } else {
    eleTxrCache.drawElement(context, ele); // direct draw fallback
  }
};
var getZeroRotation = function getZeroRotation() {
  return 0;
};
var getLabelRotation = function getLabelRotation(r, ele) {
  return r.getTextAngle(ele, null);
};
var getSourceLabelRotation = function getSourceLabelRotation(r, ele) {
  return r.getTextAngle(ele, 'source');
};
var getTargetLabelRotation = function getTargetLabelRotation(r, ele) {
  return r.getTextAngle(ele, 'target');
};
var getOpacity = function getOpacity(r, ele) {
  return ele.effectiveOpacity();
};
var getTextOpacity = function getTextOpacity(e, ele) {
  return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();
};
CRp$a.drawCachedElement = function (context, ele, pxRatio, extent, lvl, requestHighQuality) {
  var r = this;
  var _r$data = r.data,
    eleTxrCache = _r$data.eleTxrCache,
    lblTxrCache = _r$data.lblTxrCache,
    slbTxrCache = _r$data.slbTxrCache,
    tlbTxrCache = _r$data.tlbTxrCache;
  var bb = ele.boundingBox();
  var reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;
  if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
    return;
  }
  if (!extent || boundingBoxesIntersect(bb, extent)) {
    var isEdge = ele.isEdge();
    var badLine = ele.element()._private.rscratch.badLine;
    r.drawElementUnderlay(context, ele);
    r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);
    if (!isEdge || !badLine) {
      r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);
    }
    if (isEdge && !badLine) {
      r.drawCachedElementPortion(context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation, getTextOpacity);
      r.drawCachedElementPortion(context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation, getTextOpacity);
    }
    r.drawElementOverlay(context, ele);
  }
};
CRp$a.drawElements = function (context, eles) {
  var r = this;
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    r.drawElement(context, ele);
  }
};
CRp$a.drawCachedElements = function (context, eles, pxRatio, extent) {
  var r = this;
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    r.drawCachedElement(context, ele, pxRatio, extent);
  }
};
CRp$a.drawCachedNodes = function (context, eles, pxRatio, extent) {
  var r = this;
  for (var i = 0; i < eles.length; i++) {
    var ele = eles[i];
    if (!ele.isNode()) {
      continue;
    }
    r.drawCachedElement(context, ele, pxRatio, extent);
  }
};
CRp$a.drawLayeredElements = function (context, eles, pxRatio, extent) {
  var r = this;
  var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);
  if (layers) {
    for (var i = 0; i < layers.length; i++) {
      var layer = layers[i];
      var bb = layer.bb;
      if (bb.w === 0 || bb.h === 0) {
        continue;
      }
      context.drawImage(layer.canvas, bb.x1, bb.y1, bb.w, bb.h);
    }
  } else {
    // fall back on plain caching if no layers
    r.drawCachedElements(context, eles, pxRatio, extent);
  }
};

var CRp$9 = {};
CRp$9.drawEdge = function (context, edge, shiftToOriginWithBb) {
  var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  var r = this;
  var rs = edge._private.rscratch;
  if (shouldDrawOpacity && !edge.visible()) {
    return;
  }

  // if bezier ctrl pts can not be calculated, then die
  if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
    // isNaN in case edge is impossible and browser bugs (e.g. safari)
    return;
  }
  var bb;
  if (shiftToOriginWithBb) {
    bb = shiftToOriginWithBb;
    context.translate(-bb.x1, -bb.y1);
  }
  var opacity = shouldDrawOpacity ? edge.pstyle('opacity').value : 1;
  var lineOpacity = shouldDrawOpacity ? edge.pstyle('line-opacity').value : 1;
  var curveStyle = edge.pstyle('curve-style').value;
  var lineStyle = edge.pstyle('line-style').value;
  var edgeWidth = edge.pstyle('width').pfValue;
  var lineCap = edge.pstyle('line-cap').value;
  var lineOutlineWidth = edge.pstyle('line-outline-width').value;
  var lineOutlineColor = edge.pstyle('line-outline-color').value;
  var effectiveLineOpacity = opacity * lineOpacity;
  // separate arrow opacity would require arrow-opacity property
  var effectiveArrowOpacity = opacity * lineOpacity;
  var drawLine = function drawLine() {
    var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
    if (curveStyle === 'straight-triangle') {
      r.eleStrokeStyle(context, edge, strokeOpacity);
      r.drawEdgeTrianglePath(edge, context, rs.allpts);
    } else {
      context.lineWidth = edgeWidth;
      context.lineCap = lineCap;
      r.eleStrokeStyle(context, edge, strokeOpacity);
      r.drawEdgePath(edge, context, rs.allpts, lineStyle);
      context.lineCap = 'butt'; // reset for other drawing functions
    }
  };
  var drawLineOutline = function drawLineOutline() {
    var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
    context.lineWidth = edgeWidth + lineOutlineWidth;
    context.lineCap = lineCap;
    if (lineOutlineWidth > 0) {
      r.colorStrokeStyle(context, lineOutlineColor[0], lineOutlineColor[1], lineOutlineColor[2], strokeOpacity);
    } else {
      // do not draw any lineOutline
      context.lineCap = 'butt'; // reset for other drawing functions
      return;
    }
    if (curveStyle === 'straight-triangle') {
      r.drawEdgeTrianglePath(edge, context, rs.allpts);
    } else {
      r.drawEdgePath(edge, context, rs.allpts, lineStyle);
      context.lineCap = 'butt'; // reset for other drawing functions
    }
  };
  var drawOverlay = function drawOverlay() {
    if (!shouldDrawOverlay) {
      return;
    }
    r.drawEdgeOverlay(context, edge);
  };
  var drawUnderlay = function drawUnderlay() {
    if (!shouldDrawOverlay) {
      return;
    }
    r.drawEdgeUnderlay(context, edge);
  };
  var drawArrows = function drawArrows() {
    var arrowOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveArrowOpacity;
    r.drawArrowheads(context, edge, arrowOpacity);
  };
  var drawText = function drawText() {
    r.drawElementText(context, edge, null, drawLabel);
  };
  context.lineJoin = 'round';
  var ghost = edge.pstyle('ghost').value === 'yes';
  if (ghost) {
    var gx = edge.pstyle('ghost-offset-x').pfValue;
    var gy = edge.pstyle('ghost-offset-y').pfValue;
    var ghostOpacity = edge.pstyle('ghost-opacity').value;
    var effectiveGhostOpacity = effectiveLineOpacity * ghostOpacity;
    context.translate(gx, gy);
    drawLine(effectiveGhostOpacity);
    drawArrows(effectiveGhostOpacity);
    context.translate(-gx, -gy);
  } else {
    drawLineOutline();
  }
  drawUnderlay();
  drawLine();
  drawArrows();
  drawOverlay();
  drawText();
  if (shiftToOriginWithBb) {
    context.translate(bb.x1, bb.y1);
  }
};
var drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {
  if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
    throw new Error('Invalid state');
  }
  return function (context, edge) {
    if (!edge.visible()) {
      return;
    }
    var opacity = edge.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
    if (opacity === 0) {
      return;
    }
    var r = this;
    var usePaths = r.usePaths();
    var rs = edge._private.rscratch;
    var padding = edge.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
    var width = 2 * padding;
    var color = edge.pstyle("".concat(overlayOrUnderlay, "-color")).value;
    context.lineWidth = width;
    if (rs.edgeType === 'self' && !usePaths) {
      context.lineCap = 'butt';
    } else {
      context.lineCap = 'round';
    }
    r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
    r.drawEdgePath(edge, context, rs.allpts, 'solid');
  };
};
CRp$9.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');
CRp$9.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');
CRp$9.drawEdgePath = function (edge, context, pts, type) {
  var rs = edge._private.rscratch;
  var canvasCxt = context;
  var path;
  var pathCacheHit = false;
  var usePaths = this.usePaths();
  var lineDashPattern = edge.pstyle('line-dash-pattern').pfValue;
  var lineDashOffset = edge.pstyle('line-dash-offset').pfValue;
  if (usePaths) {
    var pathCacheKey = pts.join('$');
    var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;
    if (keyMatches) {
      path = context = rs.pathCache;
      pathCacheHit = true;
    } else {
      path = context = new Path2D();
      rs.pathCacheKey = pathCacheKey;
      rs.pathCache = path;
    }
  }
  if (canvasCxt.setLineDash) {
    // for very outofdate browsers
    switch (type) {
      case 'dotted':
        canvasCxt.setLineDash([1, 1]);
        break;
      case 'dashed':
        canvasCxt.setLineDash(lineDashPattern);
        canvasCxt.lineDashOffset = lineDashOffset;
        break;
      case 'solid':
        canvasCxt.setLineDash([]);
        break;
    }
  }
  if (!pathCacheHit && !rs.badLine) {
    if (context.beginPath) {
      context.beginPath();
    }
    context.moveTo(pts[0], pts[1]);
    switch (rs.edgeType) {
      case 'bezier':
      case 'self':
      case 'compound':
      case 'multibezier':
        for (var i = 2; i + 3 < pts.length; i += 4) {
          context.quadraticCurveTo(pts[i], pts[i + 1], pts[i + 2], pts[i + 3]);
        }
        break;
      case 'straight':
      case 'haystack':
        for (var _i = 2; _i + 1 < pts.length; _i += 2) {
          context.lineTo(pts[_i], pts[_i + 1]);
        }
        break;
      case 'segments':
        if (rs.isRound) {
          var _iterator = _createForOfIteratorHelper(rs.roundCorners),
            _step;
          try {
            for (_iterator.s(); !(_step = _iterator.n()).done;) {
              var corner = _step.value;
              drawPreparedRoundCorner(context, corner);
            }
          } catch (err) {
            _iterator.e(err);
          } finally {
            _iterator.f();
          }
          context.lineTo(pts[pts.length - 2], pts[pts.length - 1]);
        } else {
          for (var _i2 = 2; _i2 + 1 < pts.length; _i2 += 2) {
            context.lineTo(pts[_i2], pts[_i2 + 1]);
          }
        }
        break;
    }
  }
  context = canvasCxt;
  if (usePaths) {
    context.stroke(path);
  } else {
    context.stroke();
  }

  // reset any line dashes
  if (context.setLineDash) {
    // for very outofdate browsers
    context.setLineDash([]);
  }
};
CRp$9.drawEdgeTrianglePath = function (edge, context, pts) {
  // use line stroke style for triangle fill style
  context.fillStyle = context.strokeStyle;
  var edgeWidth = edge.pstyle('width').pfValue;
  for (var i = 0; i + 1 < pts.length; i += 2) {
    var vector = [pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]];
    var length = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);
    var normal = [vector[1] / length, -vector[0] / length];
    var triangleHead = [normal[0] * edgeWidth / 2, normal[1] * edgeWidth / 2];
    context.beginPath();
    context.moveTo(pts[i] - triangleHead[0], pts[i + 1] - triangleHead[1]);
    context.lineTo(pts[i] + triangleHead[0], pts[i + 1] + triangleHead[1]);
    context.lineTo(pts[i + 2], pts[i + 3]);
    context.closePath();
    context.fill();
  }
};
CRp$9.drawArrowheads = function (context, edge, opacity) {
  var rs = edge._private.rscratch;
  var isHaystack = rs.edgeType === 'haystack';
  if (!isHaystack) {
    this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);
  }
  this.drawArrowhead(context, edge, 'mid-target', rs.midX, rs.midY, rs.midtgtArrowAngle, opacity);
  this.drawArrowhead(context, edge, 'mid-source', rs.midX, rs.midY, rs.midsrcArrowAngle, opacity);
  if (!isHaystack) {
    this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);
  }
};
CRp$9.drawArrowhead = function (context, edge, prefix, x, y, angle, opacity) {
  if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
    return;
  }
  var self = this;
  var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  if (arrowShape === 'none') {
    return;
  }
  var arrowClearFill = edge.pstyle(prefix + '-arrow-fill').value === 'hollow' ? 'both' : 'filled';
  var arrowFill = edge.pstyle(prefix + '-arrow-fill').value;
  var edgeWidth = edge.pstyle('width').pfValue;
  var pArrowWidth = edge.pstyle(prefix + '-arrow-width');
  var arrowWidth = pArrowWidth.value === 'match-line' ? edgeWidth : pArrowWidth.pfValue;
  if (pArrowWidth.units === '%') arrowWidth *= edgeWidth;
  var edgeOpacity = edge.pstyle('opacity').value;
  if (opacity === undefined) {
    opacity = edgeOpacity;
  }
  var gco = context.globalCompositeOperation;
  if (opacity !== 1 || arrowFill === 'hollow') {
    // then extra clear is needed
    context.globalCompositeOperation = 'destination-out';
    self.colorFillStyle(context, 255, 255, 255, 1);
    self.colorStrokeStyle(context, 255, 255, 255, 1);
    self.drawArrowShape(edge, context, arrowClearFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
    context.globalCompositeOperation = gco;
  } // otherwise, the opaque arrow clears it for free :)

  var color = edge.pstyle(prefix + '-arrow-color').value;
  self.colorFillStyle(context, color[0], color[1], color[2], opacity);
  self.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  self.drawArrowShape(edge, context, arrowFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
};
CRp$9.drawArrowShape = function (edge, context, fill, edgeWidth, shape, shapeWidth, x, y, angle) {
  var r = this;
  var usePaths = this.usePaths() && shape !== 'triangle-cross';
  var pathCacheHit = false;
  var path;
  var canvasContext = context;
  var translation = {
    x: x,
    y: y
  };
  var scale = edge.pstyle('arrow-scale').value;
  var size = this.getArrowWidth(edgeWidth, scale);
  var shapeImpl = r.arrowShapes[shape];
  if (usePaths) {
    var cache = r.arrowPathCache = r.arrowPathCache || [];
    var key = hashString(shape);
    var cachedPath = cache[key];
    if (cachedPath != null) {
      path = context = cachedPath;
      pathCacheHit = true;
    } else {
      path = context = new Path2D();
      cache[key] = path;
    }
  }
  if (!pathCacheHit) {
    if (context.beginPath) {
      context.beginPath();
    }
    if (usePaths) {
      // store in the path cache with values easily manipulated later
      shapeImpl.draw(context, 1, 0, {
        x: 0,
        y: 0
      }, 1);
    } else {
      shapeImpl.draw(context, size, angle, translation, edgeWidth);
    }
    if (context.closePath) {
      context.closePath();
    }
  }
  context = canvasContext;
  if (usePaths) {
    // set transform to arrow position/orientation
    context.translate(x, y);
    context.rotate(angle);
    context.scale(size, size);
  }
  if (fill === 'filled' || fill === 'both') {
    if (usePaths) {
      context.fill(path);
    } else {
      context.fill();
    }
  }
  if (fill === 'hollow' || fill === 'both') {
    context.lineWidth = shapeWidth / (usePaths ? size : 1);
    context.lineJoin = 'miter';
    if (usePaths) {
      context.stroke(path);
    } else {
      context.stroke();
    }
  }
  if (usePaths) {
    // reset transform by applying inverse
    context.scale(1 / size, 1 / size);
    context.rotate(-angle);
    context.translate(-x, -y);
  }
};

var CRp$8 = {};
CRp$8.safeDrawImage = function (context, img, ix, iy, iw, ih, x, y, w, h) {
  // detect problematic cases for old browsers with bad images (cheaper than try-catch)
  if (iw <= 0 || ih <= 0 || w <= 0 || h <= 0) {
    return;
  }
  try {
    context.drawImage(img, ix, iy, iw, ih, x, y, w, h);
  } catch (e) {
    warn(e);
  }
};
CRp$8.drawInscribedImage = function (context, img, node, index, nodeOpacity) {
  var r = this;
  var pos = node.position();
  var nodeX = pos.x;
  var nodeY = pos.y;
  var styleObj = node.cy().style();
  var getIndexedStyle = styleObj.getIndexedStyle.bind(styleObj);
  var fit = getIndexedStyle(node, 'background-fit', 'value', index);
  var repeat = getIndexedStyle(node, 'background-repeat', 'value', index);
  var nodeW = node.width();
  var nodeH = node.height();
  var paddingX2 = node.padding() * 2;
  var nodeTW = nodeW + (getIndexedStyle(node, 'background-width-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  var nodeTH = nodeH + (getIndexedStyle(node, 'background-height-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  var rs = node._private.rscratch;
  var clip = getIndexedStyle(node, 'background-clip', 'value', index);
  var shouldClip = clip === 'node';
  var imgOpacity = getIndexedStyle(node, 'background-image-opacity', 'value', index) * nodeOpacity;
  var smooth = getIndexedStyle(node, 'background-image-smoothing', 'value', index);
  var cornerRadius = node.pstyle('corner-radius').value;
  if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  var imgW = img.width || img.cachedW;
  var imgH = img.height || img.cachedH;

  // workaround for broken browsers like ie
  if (null == imgW || null == imgH) {
    document.body.appendChild(img); // eslint-disable-line no-undef

    imgW = img.cachedW = img.width || img.offsetWidth;
    imgH = img.cachedH = img.height || img.offsetHeight;
    document.body.removeChild(img); // eslint-disable-line no-undef
  }
  var w = imgW;
  var h = imgH;
  if (getIndexedStyle(node, 'background-width', 'value', index) !== 'auto') {
    if (getIndexedStyle(node, 'background-width', 'units', index) === '%') {
      w = getIndexedStyle(node, 'background-width', 'pfValue', index) * nodeTW;
    } else {
      w = getIndexedStyle(node, 'background-width', 'pfValue', index);
    }
  }
  if (getIndexedStyle(node, 'background-height', 'value', index) !== 'auto') {
    if (getIndexedStyle(node, 'background-height', 'units', index) === '%') {
      h = getIndexedStyle(node, 'background-height', 'pfValue', index) * nodeTH;
    } else {
      h = getIndexedStyle(node, 'background-height', 'pfValue', index);
    }
  }
  if (w === 0 || h === 0) {
    return; // no point in drawing empty image (and chrome is broken in this case)
  }
  if (fit === 'contain') {
    var scale = Math.min(nodeTW / w, nodeTH / h);
    w *= scale;
    h *= scale;
  } else if (fit === 'cover') {
    var scale = Math.max(nodeTW / w, nodeTH / h);
    w *= scale;
    h *= scale;
  }
  var x = nodeX - nodeTW / 2; // left
  var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);
  var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);
  if (posXUnits === '%') {
    x += (nodeTW - w) * posXPfVal;
  } else {
    x += posXPfVal;
  }
  var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);
  var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);
  if (offXUnits === '%') {
    x += (nodeTW - w) * offXPfVal;
  } else {
    x += offXPfVal;
  }
  var y = nodeY - nodeTH / 2; // top
  var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);
  var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);
  if (posYUnits === '%') {
    y += (nodeTH - h) * posYPfVal;
  } else {
    y += posYPfVal;
  }
  var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);
  var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);
  if (offYUnits === '%') {
    y += (nodeTH - h) * offYPfVal;
  } else {
    y += offYPfVal;
  }
  if (rs.pathCache) {
    x -= nodeX;
    y -= nodeY;
    nodeX = 0;
    nodeY = 0;
  }
  var gAlpha = context.globalAlpha;
  context.globalAlpha = imgOpacity;
  var smoothingEnabled = r.getImgSmoothing(context);
  var isSmoothingSwitched = false;
  if (smooth === 'no' && smoothingEnabled) {
    r.setImgSmoothing(context, false);
    isSmoothingSwitched = true;
  } else if (smooth === 'yes' && !smoothingEnabled) {
    r.setImgSmoothing(context, true);
    isSmoothingSwitched = true;
  }
  if (repeat === 'no-repeat') {
    if (shouldClip) {
      context.save();
      if (rs.pathCache) {
        context.clip(rs.pathCache);
      } else {
        r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
        context.clip();
      }
    }
    r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);
    if (shouldClip) {
      context.restore();
    }
  } else {
    var pattern = context.createPattern(img, repeat);
    context.fillStyle = pattern;
    r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
    context.translate(x, y);
    context.fill();
    context.translate(-x, -y);
  }
  context.globalAlpha = gAlpha;
  if (isSmoothingSwitched) {
    r.setImgSmoothing(context, smoothingEnabled);
  }
};

var CRp$7 = {};
CRp$7.eleTextBiggerThanMin = function (ele, scale) {
  if (!scale) {
    var zoom = ele.cy().zoom();
    var pxRatio = this.getPixelRatio();
    var lvl = Math.ceil(log2(zoom * pxRatio)); // the effective texture level

    scale = Math.pow(2, lvl);
  }
  var computedSize = ele.pstyle('font-size').pfValue * scale;
  var minSize = ele.pstyle('min-zoomed-font-size').pfValue;
  if (computedSize < minSize) {
    return false;
  }
  return true;
};
CRp$7.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {
  var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  var r = this;
  if (force == null) {
    if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {
      return;
    }
  } else if (force === false) {
    return;
  }
  if (ele.isNode()) {
    var label = ele.pstyle('label');
    if (!label || !label.value) {
      return;
    }
    var justification = r.getLabelJustification(ele);
    context.textAlign = justification;
    context.textBaseline = 'bottom';
  } else {
    var badLine = ele.element()._private.rscratch.badLine;
    var _label = ele.pstyle('label');
    var srcLabel = ele.pstyle('source-label');
    var tgtLabel = ele.pstyle('target-label');
    if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {
      return;
    }
    context.textAlign = 'center';
    context.textBaseline = 'bottom';
  }
  var applyRotation = !shiftToOriginWithBb;
  var bb;
  if (shiftToOriginWithBb) {
    bb = shiftToOriginWithBb;
    context.translate(-bb.x1, -bb.y1);
  }
  if (prefix == null) {
    r.drawText(context, ele, null, applyRotation, useEleOpacity);
    if (ele.isEdge()) {
      r.drawText(context, ele, 'source', applyRotation, useEleOpacity);
      r.drawText(context, ele, 'target', applyRotation, useEleOpacity);
    }
  } else {
    r.drawText(context, ele, prefix, applyRotation, useEleOpacity);
  }
  if (shiftToOriginWithBb) {
    context.translate(bb.x1, bb.y1);
  }
};
CRp$7.getFontCache = function (context) {
  var cache;
  this.fontCaches = this.fontCaches || [];
  for (var i = 0; i < this.fontCaches.length; i++) {
    cache = this.fontCaches[i];
    if (cache.context === context) {
      return cache;
    }
  }
  cache = {
    context: context
  };
  this.fontCaches.push(cache);
  return cache;
};

// set up canvas context with font
// returns transformed text string
CRp$7.setupTextStyle = function (context, ele) {
  var useEleOpacity = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  // Font style
  var labelStyle = ele.pstyle('font-style').strValue;
  var labelSize = ele.pstyle('font-size').pfValue + 'px';
  var labelFamily = ele.pstyle('font-family').strValue;
  var labelWeight = ele.pstyle('font-weight').strValue;
  var opacity = useEleOpacity ? ele.effectiveOpacity() * ele.pstyle('text-opacity').value : 1;
  var outlineOpacity = ele.pstyle('text-outline-opacity').value * opacity;
  var color = ele.pstyle('color').value;
  var outlineColor = ele.pstyle('text-outline-color').value;
  context.font = labelStyle + ' ' + labelWeight + ' ' + labelSize + ' ' + labelFamily;
  context.lineJoin = 'round'; // so text outlines aren't jagged

  this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  this.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], outlineOpacity);
};
function circle(ctx, x, y, width, height) {
  var diameter = Math.min(width, height);
  var radius = diameter / 2;
  var centerX = x + width / 2;
  var centerY = y + height / 2;
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.closePath();
}
function roundRect(ctx, x, y, width, height) {
  var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;
  var r = Math.min(radius, width / 2, height / 2); // prevent overflow
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + width - r, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + r);
  ctx.lineTo(x + width, y + height - r);
  ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
  ctx.lineTo(x + r, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - r);
  ctx.lineTo(x, y + r);
  ctx.quadraticCurveTo(x, y, x + r, y);
  ctx.closePath();
}
CRp$7.getTextAngle = function (ele, prefix) {
  var theta;
  var _p = ele._private;
  var rscratch = _p.rscratch;
  var pdash = prefix ? prefix + '-' : '';
  var rotation = ele.pstyle(pdash + 'text-rotation');
  if (rotation.strValue === 'autorotate') {
    var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);
    theta = ele.isEdge() ? textAngle : 0;
  } else if (rotation.strValue === 'none') {
    theta = 0;
  } else {
    theta = rotation.pfValue;
  }
  return theta;
};
CRp$7.drawText = function (context, ele, prefix) {
  var applyRotation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var useEleOpacity = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  var _p = ele._private;
  var rscratch = _p.rscratch;
  var parentOpacity = useEleOpacity ? ele.effectiveOpacity() : 1;
  if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {
    return;
  }

  // use 'main' as an alias for the main label (i.e. null prefix)
  if (prefix === 'main') {
    prefix = null;
  }
  var textX = getPrefixedProperty(rscratch, 'labelX', prefix);
  var textY = getPrefixedProperty(rscratch, 'labelY', prefix);
  var orgTextX, orgTextY; // used for rotation
  var text = this.getLabelText(ele, prefix);
  if (text != null && text !== '' && !isNaN(textX) && !isNaN(textY)) {
    this.setupTextStyle(context, ele, useEleOpacity);
    var pdash = prefix ? prefix + '-' : '';
    var textW = getPrefixedProperty(rscratch, 'labelWidth', prefix);
    var textH = getPrefixedProperty(rscratch, 'labelHeight', prefix);
    var marginX = ele.pstyle(pdash + 'text-margin-x').pfValue;
    var marginY = ele.pstyle(pdash + 'text-margin-y').pfValue;
    var isEdge = ele.isEdge();
    var halign = ele.pstyle('text-halign').value;
    var valign = ele.pstyle('text-valign').value;
    if (isEdge) {
      halign = 'center';
      valign = 'center';
    }
    textX += marginX;
    textY += marginY;
    var theta;
    if (!applyRotation) {
      theta = 0;
    } else {
      theta = this.getTextAngle(ele, prefix);
    }
    if (theta !== 0) {
      orgTextX = textX;
      orgTextY = textY;
      context.translate(orgTextX, orgTextY);
      context.rotate(theta);
      textX = 0;
      textY = 0;
    }
    switch (valign) {
      case 'top':
        break;
      case 'center':
        textY += textH / 2;
        break;
      case 'bottom':
        textY += textH;
        break;
    }
    var backgroundOpacity = ele.pstyle('text-background-opacity').value;
    var borderOpacity = ele.pstyle('text-border-opacity').value;
    var textBorderWidth = ele.pstyle('text-border-width').pfValue;
    var backgroundPadding = ele.pstyle('text-background-padding').pfValue;
    var styleShape = ele.pstyle('text-background-shape').strValue;
    var rounded = styleShape === 'round-rectangle' || styleShape === 'roundrectangle';
    var circled = styleShape === 'circle';
    var roundRadius = 2;
    if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {
      var textFill = context.fillStyle;
      var textStroke = context.strokeStyle;
      var textLineWidth = context.lineWidth;
      var textBackgroundColor = ele.pstyle('text-background-color').value;
      var textBorderColor = ele.pstyle('text-border-color').value;
      var textBorderStyle = ele.pstyle('text-border-style').value;
      var doFill = backgroundOpacity > 0;
      var doStroke = textBorderWidth > 0 && borderOpacity > 0;
      var bgX = textX - backgroundPadding;
      switch (halign) {
        case 'left':
          bgX -= textW;
          break;
        case 'center':
          bgX -= textW / 2;
          break;
      }
      var bgY = textY - textH - backgroundPadding;
      var bgW = textW + 2 * backgroundPadding;
      var bgH = textH + 2 * backgroundPadding;
      if (doFill) {
        context.fillStyle = "rgba(".concat(textBackgroundColor[0], ",").concat(textBackgroundColor[1], ",").concat(textBackgroundColor[2], ",").concat(backgroundOpacity * parentOpacity, ")");
      }
      if (doStroke) {
        context.strokeStyle = "rgba(".concat(textBorderColor[0], ",").concat(textBorderColor[1], ",").concat(textBorderColor[2], ",").concat(borderOpacity * parentOpacity, ")");
        context.lineWidth = textBorderWidth;
        if (context.setLineDash) {
          switch (textBorderStyle) {
            case 'dotted':
              context.setLineDash([1, 1]);
              break;
            case 'dashed':
              context.setLineDash([4, 2]);
              break;
            case 'double':
              context.lineWidth = textBorderWidth / 4;
              context.setLineDash([]);
              break;
            case 'solid':
            default:
              context.setLineDash([]);
              break;
          }
        }
      }
      if (rounded) {
        context.beginPath();
        roundRect(context, bgX, bgY, bgW, bgH, roundRadius);
      } else if (circled) {
        context.beginPath();
        circle(context, bgX, bgY, bgW, bgH);
      } else {
        context.beginPath();
        context.rect(bgX, bgY, bgW, bgH);
      }
      if (doFill) context.fill();
      if (doStroke) context.stroke();

      // Double border pass for 'double' style
      if (doStroke && textBorderStyle === 'double') {
        var whiteWidth = textBorderWidth / 2;
        context.beginPath();
        if (rounded) {
          roundRect(context, bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth, roundRadius);
        } else {
          context.rect(bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth);
        }
        context.stroke();
      }
      context.fillStyle = textFill;
      context.strokeStyle = textStroke;
      context.lineWidth = textLineWidth;
      if (context.setLineDash) context.setLineDash([]);
    }
    var lineWidth = 2 * ele.pstyle('text-outline-width').pfValue; // *2 b/c the stroke is drawn centred on the middle

    if (lineWidth > 0) {
      context.lineWidth = lineWidth;
    }
    if (ele.pstyle('text-wrap').value === 'wrap') {
      var lines = getPrefixedProperty(rscratch, 'labelWrapCachedLines', prefix);
      var lineHeight = getPrefixedProperty(rscratch, 'labelLineHeight', prefix);
      var halfTextW = textW / 2;
      var justification = this.getLabelJustification(ele);
      if (justification === 'auto') ; else if (halign === 'left') {
        // auto justification : right
        if (justification === 'left') {
          textX += -textW;
        } else if (justification === 'center') {
          textX += -halfTextW;
        } // else same as auto
      } else if (halign === 'center') {
        // auto justfication : center
        if (justification === 'left') {
          textX += -halfTextW;
        } else if (justification === 'right') {
          textX += halfTextW;
        } // else same as auto
      } else if (halign === 'right') {
        // auto justification : left
        if (justification === 'center') {
          textX += halfTextW;
        } else if (justification === 'right') {
          textX += textW;
        } // else same as auto
      }
      switch (valign) {
        case 'top':
          textY -= (lines.length - 1) * lineHeight;
          break;
        case 'center':
        case 'bottom':
          textY -= (lines.length - 1) * lineHeight;
          break;
      }
      for (var l = 0; l < lines.length; l++) {
        if (lineWidth > 0) {
          context.strokeText(lines[l], textX, textY);
        }
        context.fillText(lines[l], textX, textY);
        textY += lineHeight;
      }
    } else {
      if (lineWidth > 0) {
        context.strokeText(text, textX, textY);
      }
      context.fillText(text, textX, textY);
    }
    if (theta !== 0) {
      context.rotate(-theta);
      context.translate(-orgTextX, -orgTextY);
    }
  }
};

/* global Path2D */

var CRp$6 = {};
CRp$6.drawNode = function (context, node, shiftToOriginWithBb) {
  var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  var r = this;
  var nodeWidth, nodeHeight;
  var _p = node._private;
  var rs = _p.rscratch;
  var pos = node.position();
  if (!number$1(pos.x) || !number$1(pos.y)) {
    return; // can't draw node with undefined position
  }
  if (shouldDrawOpacity && !node.visible()) {
    return;
  }
  var eleOpacity = shouldDrawOpacity ? node.effectiveOpacity() : 1;
  var usePaths = r.usePaths();
  var path;
  var pathCacheHit = false;
  var padding = node.padding();
  nodeWidth = node.width() + 2 * padding;
  nodeHeight = node.height() + 2 * padding;

  //
  // setup shift

  var bb;
  if (shiftToOriginWithBb) {
    bb = shiftToOriginWithBb;
    context.translate(-bb.x1, -bb.y1);
  }

  //
  // load bg image

  var bgImgProp = node.pstyle('background-image');
  var urls = bgImgProp.value;
  var urlDefined = new Array(urls.length);
  var image = new Array(urls.length);
  var numImages = 0;
  for (var i = 0; i < urls.length; i++) {
    var url = urls[i];
    var defd = urlDefined[i] = url != null && url !== 'none';
    if (defd) {
      var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);
      numImages++;

      // get image, and if not loaded then ask to redraw when later loaded
      image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {
        _p.backgroundTimestamp = Date.now();
        node.emitAndNotify('background');
      });
    }
  }

  //
  // setup styles

  var darkness = node.pstyle('background-blacken').value;
  var borderWidth = node.pstyle('border-width').pfValue;
  var bgOpacity = node.pstyle('background-opacity').value * eleOpacity;
  var borderColor = node.pstyle('border-color').value;
  var borderStyle = node.pstyle('border-style').value;
  var borderJoin = node.pstyle('border-join').value;
  var borderCap = node.pstyle('border-cap').value;
  var borderPosition = node.pstyle('border-position').value;
  var borderPattern = node.pstyle('border-dash-pattern').pfValue;
  var borderOffset = node.pstyle('border-dash-offset').pfValue;
  var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;
  var outlineWidth = node.pstyle('outline-width').pfValue;
  var outlineColor = node.pstyle('outline-color').value;
  var outlineStyle = node.pstyle('outline-style').value;
  var outlineOpacity = node.pstyle('outline-opacity').value * eleOpacity;
  var outlineOffset = node.pstyle('outline-offset').value;
  var cornerRadius = node.pstyle('corner-radius').value;
  if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  var setupShapeColor = function setupShapeColor() {
    var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
    r.eleFillStyle(context, node, bgOpy);
  };
  var setupBorderColor = function setupBorderColor() {
    var bdrOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : borderOpacity;
    r.colorStrokeStyle(context, borderColor[0], borderColor[1], borderColor[2], bdrOpy);
  };
  var setupOutlineColor = function setupOutlineColor() {
    var otlnOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : outlineOpacity;
    r.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], otlnOpy);
  };

  //
  // setup shape

  var getPath = function getPath(width, height, shape, points) {
    var pathCache = r.nodePathCache = r.nodePathCache || [];
    var key = hashStrings(shape === 'polygon' ? shape + ',' + points.join(',') : shape, '' + height, '' + width, '' + cornerRadius);
    var cachedPath = pathCache[key];
    var path;
    var cacheHit = false;
    if (cachedPath != null) {
      path = cachedPath;
      cacheHit = true;
      rs.pathCache = path;
    } else {
      path = new Path2D();
      pathCache[key] = rs.pathCache = path;
    }
    return {
      path: path,
      cacheHit: cacheHit
    };
  };
  var styleShape = node.pstyle('shape').strValue;
  var shapePts = node.pstyle('shape-polygon-points').pfValue;
  if (usePaths) {
    context.translate(pos.x, pos.y);
    var shapePath = getPath(nodeWidth, nodeHeight, styleShape, shapePts);
    path = shapePath.path;
    pathCacheHit = shapePath.cacheHit;
  }
  var drawShape = function drawShape() {
    if (!pathCacheHit) {
      var npos = pos;
      if (usePaths) {
        npos = {
          x: 0,
          y: 0
        };
      }
      r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight, cornerRadius, rs);
    }
    if (usePaths) {
      context.fill(path);
    } else {
      context.fill();
    }
  };
  var drawImages = function drawImages() {
    var nodeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
    var inside = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    var prevBging = _p.backgrounding;
    var totalCompleted = 0;
    for (var _i = 0; _i < image.length; _i++) {
      var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);
      if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {
        totalCompleted++;
        continue;
      }
      if (urlDefined[_i] && image[_i].complete && !image[_i].error) {
        totalCompleted++;
        r.drawInscribedImage(context, image[_i], node, _i, nodeOpacity);
      }
    }
    _p.backgrounding = !(totalCompleted === numImages);
    if (prevBging !== _p.backgrounding) {
      // update style b/c :backgrounding state changed
      node.updateStyle(false);
    }
  };
  var drawPie = function drawPie() {
    var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var pieOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
    if (r.hasPie(node)) {
      r.drawPie(context, node, pieOpacity);

      // redraw/restore path if steps after pie need it
      if (redrawShape) {
        if (!usePaths) {
          r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
        }
      }
    }
  };
  var drawStripe = function drawStripe() {
    var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var stripeOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
    if (r.hasStripe(node)) {
      context.save();
      if (usePaths) {
        context.clip(rs.pathCache);
      } else {
        r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
        context.clip();
      }
      r.drawStripe(context, node, stripeOpacity);
      context.restore();

      // redraw/restore path if steps after stripes need it
      if (redrawShape) {
        if (!usePaths) {
          r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
        }
      }
    }
  };
  var darken = function darken() {
    var darkenOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
    var opacity = (darkness > 0 ? darkness : -darkness) * darkenOpacity;
    var c = darkness > 0 ? 0 : 255;
    if (darkness !== 0) {
      r.colorFillStyle(context, c, c, c, opacity);
      if (usePaths) {
        context.fill(path);
      } else {
        context.fill();
      }
    }
  };
  var drawBorder = function drawBorder() {
    if (borderWidth > 0) {
      context.lineWidth = borderWidth;
      context.lineCap = borderCap;
      context.lineJoin = borderJoin;
      if (context.setLineDash) {
        // for very outofdate browsers
        switch (borderStyle) {
          case 'dotted':
            context.setLineDash([1, 1]);
            break;
          case 'dashed':
            context.setLineDash(borderPattern);
            context.lineDashOffset = borderOffset;
            break;
          case 'solid':
          case 'double':
            context.setLineDash([]);
            break;
        }
      }
      if (borderPosition !== 'center') {
        context.save();
        context.lineWidth *= 2;
        if (borderPosition === 'inside') {
          usePaths ? context.clip(path) : context.clip();
        } else {
          var region = new Path2D();
          region.rect(-nodeWidth / 2 - borderWidth, -nodeHeight / 2 - borderWidth, nodeWidth + 2 * borderWidth, nodeHeight + 2 * borderWidth);
          region.addPath(path);
          context.clip(region, 'evenodd');
        }
        usePaths ? context.stroke(path) : context.stroke();
        context.restore();
      } else {
        usePaths ? context.stroke(path) : context.stroke();
      }
      if (borderStyle === 'double') {
        context.lineWidth = borderWidth / 3;
        var gco = context.globalCompositeOperation;
        context.globalCompositeOperation = 'destination-out';
        if (usePaths) {
          context.stroke(path);
        } else {
          context.stroke();
        }
        context.globalCompositeOperation = gco;
      }

      // reset in case we changed the border style
      if (context.setLineDash) {
        // for very outofdate browsers
        context.setLineDash([]);
      }
    }
  };
  var drawOutline = function drawOutline() {
    if (outlineWidth > 0) {
      context.lineWidth = outlineWidth;
      context.lineCap = 'butt';
      if (context.setLineDash) {
        // for very outofdate browsers
        switch (outlineStyle) {
          case 'dotted':
            context.setLineDash([1, 1]);
            break;
          case 'dashed':
            context.setLineDash([4, 2]);
            break;
          case 'solid':
          case 'double':
            context.setLineDash([]);
            break;
        }
      }
      var npos = pos;
      if (usePaths) {
        npos = {
          x: 0,
          y: 0
        };
      }
      var shape = r.getNodeShape(node);
      var bWidth = borderWidth;
      if (borderPosition === 'inside') bWidth = 0;
      if (borderPosition === 'outside') bWidth *= 2;
      var scaleX = (nodeWidth + bWidth + (outlineWidth + outlineOffset)) / nodeWidth;
      var scaleY = (nodeHeight + bWidth + (outlineWidth + outlineOffset)) / nodeHeight;
      var sWidth = nodeWidth * scaleX;
      var sHeight = nodeHeight * scaleY;
      var points = r.nodeShapes[shape].points;
      var _path;
      if (usePaths) {
        var outlinePath = getPath(sWidth, sHeight, shape, points);
        _path = outlinePath.path;
      }

      // draw the outline path, either by using expanded points or by scaling 
      // the dimensions, depending on shape
      if (shape === "ellipse") {
        r.drawEllipsePath(_path || context, npos.x, npos.y, sWidth, sHeight);
      } else if (['round-diamond', 'round-heptagon', 'round-hexagon', 'round-octagon', 'round-pentagon', 'round-polygon', 'round-triangle', 'round-tag'].includes(shape)) {
        var sMult = 0;
        var offsetX = 0;
        var offsetY = 0;
        if (shape === 'round-diamond') {
          sMult = (bWidth + outlineOffset + outlineWidth) * 1.4;
        } else if (shape === 'round-heptagon') {
          sMult = (bWidth + outlineOffset + outlineWidth) * 1.075;
          offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 35;
        } else if (shape === 'round-hexagon') {
          sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
        } else if (shape === 'round-pentagon') {
          sMult = (bWidth + outlineOffset + outlineWidth) * 1.13;
          offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 15;
        } else if (shape === 'round-tag') {
          sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
          offsetX = (bWidth / 2 + outlineWidth + outlineOffset) * .07;
        } else if (shape === 'round-triangle') {
          sMult = (bWidth + outlineOffset + outlineWidth) * (Math.PI / 2);
          offsetY = -(bWidth + outlineOffset / 2 + outlineWidth) / Math.PI;
        }
        if (sMult !== 0) {
          scaleX = (nodeWidth + sMult) / nodeWidth;
          sWidth = nodeWidth * scaleX;
          if (!['round-hexagon', 'round-tag'].includes(shape)) {
            scaleY = (nodeHeight + sMult) / nodeHeight;
            sHeight = nodeHeight * scaleY;
          }
        }
        cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(sWidth, sHeight) : cornerRadius;
        var halfW = sWidth / 2;
        var halfH = sHeight / 2;
        var radius = cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2;
        var p = new Array(points.length / 2);
        var corners = new Array(points.length / 2);
        for (var _i2 = 0; _i2 < points.length / 2; _i2++) {
          p[_i2] = {
            x: npos.x + offsetX + halfW * points[_i2 * 2],
            y: npos.y + offsetY + halfH * points[_i2 * 2 + 1]
          };
        }
        var _i3,
          p1,
          p2,
          p3,
          len = p.length;
        p1 = p[len - 1];
        // for each point
        for (_i3 = 0; _i3 < len; _i3++) {
          p2 = p[_i3 % len];
          p3 = p[(_i3 + 1) % len];
          corners[_i3] = getRoundCorner(p1, p2, p3, radius);
          p1 = p2;
          p2 = p3;
        }
        r.drawRoundPolygonPath(_path || context, npos.x + offsetX, npos.y + offsetY, nodeWidth * scaleX, nodeHeight * scaleY, points, corners);
      } else if (['roundrectangle', 'round-rectangle'].includes(shape)) {
        cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
        r.drawRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
      } else if (['cutrectangle', 'cut-rectangle'].includes(shape)) {
        cornerRadius = cornerRadius === 'auto' ? getCutRectangleCornerLength() : cornerRadius;
        r.drawCutRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, null, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 4);
      } else if (['bottomroundrectangle', 'bottom-round-rectangle'].includes(shape)) {
        cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
        r.drawBottomRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
      } else if (shape === "barrel") {
        r.drawBarrelPath(_path || context, npos.x, npos.y, sWidth, sHeight);
      } else if (shape.startsWith("polygon") || ['rhomboid', 'right-rhomboid', 'round-tag', 'tag', 'vee'].includes(shape)) {
        var pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
        points = joinLines(expandPolygon(points, pad));
        r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
      } else {
        var _pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
        points = joinLines(expandPolygon(points, -_pad));
        r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
      }
      if (usePaths) {
        context.stroke(_path);
      } else {
        context.stroke();
      }
      if (outlineStyle === 'double') {
        context.lineWidth = bWidth / 3;
        var gco = context.globalCompositeOperation;
        context.globalCompositeOperation = 'destination-out';
        if (usePaths) {
          context.stroke(_path);
        } else {
          context.stroke();
        }
        context.globalCompositeOperation = gco;
      }

      // reset in case we changed the border style
      if (context.setLineDash) {
        // for very outofdate browsers
        context.setLineDash([]);
      }
    }
  };
  var drawOverlay = function drawOverlay() {
    if (shouldDrawOverlay) {
      r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);
    }
  };
  var drawUnderlay = function drawUnderlay() {
    if (shouldDrawOverlay) {
      r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);
    }
  };
  var drawText = function drawText() {
    r.drawElementText(context, node, null, drawLabel);
  };
  var ghost = node.pstyle('ghost').value === 'yes';
  if (ghost) {
    var gx = node.pstyle('ghost-offset-x').pfValue;
    var gy = node.pstyle('ghost-offset-y').pfValue;
    var ghostOpacity = node.pstyle('ghost-opacity').value;
    var effGhostOpacity = ghostOpacity * eleOpacity;
    context.translate(gx, gy);
    setupOutlineColor();
    drawOutline();
    setupShapeColor(ghostOpacity * bgOpacity);
    drawShape();
    drawImages(effGhostOpacity, true);
    setupBorderColor(ghostOpacity * borderOpacity);
    drawBorder();
    drawPie(darkness !== 0 || borderWidth !== 0);
    drawStripe(darkness !== 0 || borderWidth !== 0);
    drawImages(effGhostOpacity, false);
    darken(effGhostOpacity);
    context.translate(-gx, -gy);
  }
  if (usePaths) {
    context.translate(-pos.x, -pos.y);
  }
  drawUnderlay();
  if (usePaths) {
    context.translate(pos.x, pos.y);
  }
  setupOutlineColor();
  drawOutline();
  setupShapeColor();
  drawShape();
  drawImages(eleOpacity, true);
  setupBorderColor();
  drawBorder();
  drawPie(darkness !== 0 || borderWidth !== 0);
  drawStripe(darkness !== 0 || borderWidth !== 0);
  drawImages(eleOpacity, false);
  darken();
  if (usePaths) {
    context.translate(-pos.x, -pos.y);
  }
  drawText();
  drawOverlay();

  //
  // clean up shift

  if (shiftToOriginWithBb) {
    context.translate(bb.x1, bb.y1);
  }
};
var drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {
  if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
    throw new Error('Invalid state');
  }
  return function (context, node, pos, nodeWidth, nodeHeight) {
    var r = this;
    if (!node.visible()) {
      return;
    }
    var padding = node.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
    var opacity = node.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
    var color = node.pstyle("".concat(overlayOrUnderlay, "-color")).value;
    var shape = node.pstyle("".concat(overlayOrUnderlay, "-shape")).value;
    var radius = node.pstyle("".concat(overlayOrUnderlay, "-corner-radius")).value;
    if (opacity > 0) {
      pos = pos || node.position();
      if (nodeWidth == null || nodeHeight == null) {
        var _padding = node.padding();
        nodeWidth = node.width() + 2 * _padding;
        nodeHeight = node.height() + 2 * _padding;
      }
      r.colorFillStyle(context, color[0], color[1], color[2], opacity);
      r.nodeShapes[shape].draw(context, pos.x, pos.y, nodeWidth + padding * 2, nodeHeight + padding * 2, radius);
      context.fill();
    }
  };
};
CRp$6.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');
CRp$6.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay');

// does the node have at least one pie piece?
CRp$6.hasPie = function (node) {
  node = node[0]; // ensure ele ref

  return node._private.hasPie;
};
CRp$6.hasStripe = function (node) {
  node = node[0]; // ensure ele ref

  return node._private.hasStripe;
};
CRp$6.drawPie = function (context, node, nodeOpacity, pos) {
  node = node[0]; // ensure ele ref
  pos = pos || node.position();
  var cyStyle = node.cy().style();
  var pieSize = node.pstyle('pie-size');
  var hole = node.pstyle('pie-hole');
  var overallStartAngle = node.pstyle('pie-start-angle').pfValue;
  var x = pos.x;
  var y = pos.y;
  var nodeW = node.width();
  var nodeH = node.height();
  var radius = Math.min(nodeW, nodeH) / 2; // must fit in node
  var holeRadius;
  var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  var usePaths = this.usePaths();
  if (usePaths) {
    x = 0;
    y = 0;
  }
  if (pieSize.units === '%') {
    radius = radius * pieSize.pfValue;
  } else if (pieSize.pfValue !== undefined) {
    radius = pieSize.pfValue / 2; // diameter in pixels => radius
  }
  if (hole.units === '%') {
    holeRadius = radius * hole.pfValue;
  } else if (hole.pfValue !== undefined) {
    holeRadius = hole.pfValue / 2; // diameter in pixels => radius
  }
  if (holeRadius >= radius) {
    return; // the pie would be invisible anyway
  }
  for (var i = 1; i <= cyStyle.pieBackgroundN; i++) {
    // 1..N
    var size = node.pstyle('pie-' + i + '-background-size').value;
    var color = node.pstyle('pie-' + i + '-background-color').value;
    var opacity = node.pstyle('pie-' + i + '-background-opacity').value * nodeOpacity;
    var percent = size / 100; // map integer range [0, 100] to [0, 1]

    // percent can't push beyond 1
    if (percent + lastPercent > 1) {
      percent = 1 - lastPercent;
    }
    var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise
    angleStart += overallStartAngle; // shift by the overall pie start angle
    var angleDelta = 2 * Math.PI * percent;
    var angleEnd = angleStart + angleDelta;

    // ignore if
    // - zero size
    // - we're already beyond the full circle
    // - adding the current slice would go beyond the full circle
    if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
      continue;
    }
    if (holeRadius === 0) {
      // make a pie slice
      context.beginPath();
      context.moveTo(x, y);
      context.arc(x, y, radius, angleStart, angleEnd);
      context.closePath();
    } else {
      // make a pie slice that's like the above but with a hole in the middle
      context.beginPath();
      context.arc(x, y, radius, angleStart, angleEnd);
      context.arc(x, y, holeRadius, angleEnd, angleStart, true); // true for anticlockwise
      context.closePath();
    }
    this.colorFillStyle(context, color[0], color[1], color[2], opacity);
    context.fill();
    lastPercent += percent;
  }
};
CRp$6.drawStripe = function (context, node, nodeOpacity, pos) {
  node = node[0]; // ensure ele ref
  pos = pos || node.position();
  var cyStyle = node.cy().style();
  var x = pos.x;
  var y = pos.y;
  var nodeW = node.width();
  var nodeH = node.height();
  var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  var usePaths = this.usePaths();
  context.save();
  var direction = node.pstyle('stripe-direction').value;
  var stripeSize = node.pstyle('stripe-size');
  switch (direction) {
    case 'vertical':
      break;
    // default
    case 'righward':
      context.rotate(-Math.PI / 2);
      break;
  }
  var stripeW = nodeW;
  var stripeH = nodeH;
  if (stripeSize.units === '%') {
    stripeW = stripeW * stripeSize.pfValue;
    stripeH = stripeH * stripeSize.pfValue;
  } else if (stripeSize.pfValue !== undefined) {
    stripeW = stripeSize.pfValue;
    stripeH = stripeSize.pfValue;
  }
  if (usePaths) {
    x = 0;
    y = 0;
  }

  // shift up from the centre of the node to the top-left corner
  y -= stripeW / 2;
  x -= stripeH / 2;
  for (var i = 1; i <= cyStyle.stripeBackgroundN; i++) {
    // 1..N
    var size = node.pstyle('stripe-' + i + '-background-size').value;
    var color = node.pstyle('stripe-' + i + '-background-color').value;
    var opacity = node.pstyle('stripe-' + i + '-background-opacity').value * nodeOpacity;
    var percent = size / 100; // map integer range [0, 100] to [0, 1]

    // percent can't push beyond 1
    if (percent + lastPercent > 1) {
      percent = 1 - lastPercent;
    }

    // ignore if
    // - zero size
    // - we're already beyond the full chart
    // - adding the current slice would go beyond the full chart
    if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
      continue;
    }

    // draw rect for the current stripe
    context.beginPath();
    context.rect(x, y + stripeH * lastPercent, stripeW, stripeH * percent);
    context.closePath();
    this.colorFillStyle(context, color[0], color[1], color[2], opacity);
    context.fill();
    lastPercent += percent;
  }
  context.restore();
};

var CRp$5 = {};
var motionBlurDelay = 100;

// var isFirefox = typeof InstallTrigger !== 'undefined';

CRp$5.getPixelRatio = function () {
  var context = this.data.contexts[0];
  if (this.forcedPixelRatio != null) {
    return this.forcedPixelRatio;
  }
  var containerWindow = this.cy.window();
  var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  return (containerWindow.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef
};
CRp$5.paintCache = function (context) {
  var caches = this.paintCaches = this.paintCaches || [];
  var needToCreateCache = true;
  var cache;
  for (var i = 0; i < caches.length; i++) {
    cache = caches[i];
    if (cache.context === context) {
      needToCreateCache = false;
      break;
    }
  }
  if (needToCreateCache) {
    cache = {
      context: context
    };
    caches.push(cache);
  }
  return cache;
};
CRp$5.createGradientStyleFor = function (context, shapeStyleName, ele, fill, opacity) {
  var gradientStyle;
  var usePaths = this.usePaths();
  var colors = ele.pstyle(shapeStyleName + '-gradient-stop-colors').value,
    positions = ele.pstyle(shapeStyleName + '-gradient-stop-positions').pfValue;
  if (fill === 'radial-gradient') {
    if (ele.isEdge()) {
      var start = ele.sourceEndpoint(),
        end = ele.targetEndpoint(),
        mid = ele.midpoint();
      var d1 = dist(start, mid);
      var d2 = dist(end, mid);
      gradientStyle = context.createRadialGradient(mid.x, mid.y, 0, mid.x, mid.y, Math.max(d1, d2));
    } else {
      var pos = usePaths ? {
          x: 0,
          y: 0
        } : ele.position(),
        width = ele.paddedWidth(),
        height = ele.paddedHeight();
      gradientStyle = context.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, Math.max(width, height));
    }
  } else {
    if (ele.isEdge()) {
      var _start = ele.sourceEndpoint(),
        _end = ele.targetEndpoint();
      gradientStyle = context.createLinearGradient(_start.x, _start.y, _end.x, _end.y);
    } else {
      var _pos = usePaths ? {
          x: 0,
          y: 0
        } : ele.position(),
        _width = ele.paddedWidth(),
        _height = ele.paddedHeight(),
        halfWidth = _width / 2,
        halfHeight = _height / 2;
      var direction = ele.pstyle('background-gradient-direction').value;
      switch (direction) {
        case 'to-bottom':
          gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);
          break;
        case 'to-top':
          gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);
          break;
        case 'to-left':
          gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);
          break;
        case 'to-right':
          gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);
          break;
        case 'to-bottom-right':
        case 'to-right-bottom':
          gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y - halfHeight, _pos.x + halfWidth, _pos.y + halfHeight);
          break;
        case 'to-top-right':
        case 'to-right-top':
          gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y + halfHeight, _pos.x + halfWidth, _pos.y - halfHeight);
          break;
        case 'to-bottom-left':
        case 'to-left-bottom':
          gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y - halfHeight, _pos.x - halfWidth, _pos.y + halfHeight);
          break;
        case 'to-top-left':
        case 'to-left-top':
          gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y + halfHeight, _pos.x - halfWidth, _pos.y - halfHeight);
          break;
      }
    }
  }
  if (!gradientStyle) return null; // invalid gradient style

  var hasPositions = positions.length === colors.length;
  var length = colors.length;
  for (var i = 0; i < length; i++) {
    gradientStyle.addColorStop(hasPositions ? positions[i] : i / (length - 1), 'rgba(' + colors[i][0] + ',' + colors[i][1] + ',' + colors[i][2] + ',' + opacity + ')');
  }
  return gradientStyle;
};
CRp$5.gradientFillStyle = function (context, ele, fill, opacity) {
  var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);
  if (!gradientStyle) return null; // error
  context.fillStyle = gradientStyle;
};
CRp$5.colorFillStyle = function (context, r, g, b, a) {
  context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  // turn off for now, seems context does its own caching

  // var cache = this.paintCache(context);

  // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';

  // if( cache.fillStyle !== fillStyle ){
  //   context.fillStyle = cache.fillStyle = fillStyle;
  // }
};
CRp$5.eleFillStyle = function (context, ele, opacity) {
  var backgroundFill = ele.pstyle('background-fill').value;
  if (backgroundFill === 'linear-gradient' || backgroundFill === 'radial-gradient') {
    this.gradientFillStyle(context, ele, backgroundFill, opacity);
  } else {
    var backgroundColor = ele.pstyle('background-color').value;
    this.colorFillStyle(context, backgroundColor[0], backgroundColor[1], backgroundColor[2], opacity);
  }
};
CRp$5.gradientStrokeStyle = function (context, ele, fill, opacity) {
  var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);
  if (!gradientStyle) return null; // error
  context.strokeStyle = gradientStyle;
};
CRp$5.colorStrokeStyle = function (context, r, g, b, a) {
  context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  // turn off for now, seems context does its own caching

  // var cache = this.paintCache(context);

  // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';

  // if( cache.strokeStyle !== strokeStyle ){
  //   context.strokeStyle = cache.strokeStyle = strokeStyle;
  // }
};
CRp$5.eleStrokeStyle = function (context, ele, opacity) {
  var lineFill = ele.pstyle('line-fill').value;
  if (lineFill === 'linear-gradient' || lineFill === 'radial-gradient') {
    this.gradientStrokeStyle(context, ele, lineFill, opacity);
  } else {
    var lineColor = ele.pstyle('line-color').value;
    this.colorStrokeStyle(context, lineColor[0], lineColor[1], lineColor[2], opacity);
  }
};

// Resize canvas
CRp$5.matchCanvasSize = function (container) {
  var r = this;
  var data = r.data;
  var bb = r.findContainerClientCoords();
  var width = bb[2];
  var height = bb[3];
  var pixelRatio = r.getPixelRatio();
  var mbPxRatio = r.motionBlurPxRatio;
  if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {
    pixelRatio = mbPxRatio;
  }
  var canvasWidth = width * pixelRatio;
  var canvasHeight = height * pixelRatio;
  var canvas;
  if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {
    return; // save cycles if same
  }
  r.fontCaches = null; // resizing resets the style

  var canvasContainer = data.canvasContainer;
  canvasContainer.style.width = width + 'px';
  canvasContainer.style.height = height + 'px';
  for (var i = 0; i < r.CANVAS_LAYERS; i++) {
    canvas = data.canvases[i];
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
  }
  for (var i = 0; i < r.BUFFER_COUNT; i++) {
    canvas = data.bufferCanvases[i];
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
  }
  r.textureMult = 1;
  if (pixelRatio <= 1) {
    canvas = data.bufferCanvases[r.TEXTURE_BUFFER];
    r.textureMult = 2;
    canvas.width = canvasWidth * r.textureMult;
    canvas.height = canvasHeight * r.textureMult;
  }
  r.canvasWidth = canvasWidth;
  r.canvasHeight = canvasHeight;
  r.pixelRatio = pixelRatio;
};
CRp$5.renderTo = function (cxt, zoom, pan, pxRatio) {
  this.render({
    forcedContext: cxt,
    forcedZoom: zoom,
    forcedPan: pan,
    drawAllLayers: true,
    forcedPxRatio: pxRatio
  });
};
CRp$5.clearCanvas = function () {
  var r = this;
  var data = r.data;
  function clear(context) {
    context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  }
  clear(data.contexts[r.NODE]);
  clear(data.contexts[r.DRAG]);
};
CRp$5.render = function (options) {
  var r = this;
  options = options || staticEmptyObject();
  var cy = r.cy;
  var forcedContext = options.forcedContext;
  var drawAllLayers = options.drawAllLayers;
  var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  var forcedZoom = options.forcedZoom;
  var forcedPan = options.forcedPan;
  var pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;
  var data = r.data;
  var needDraw = data.canvasNeedsRedraw;
  var textureDraw = r.textureOnViewport && !forcedContext && (r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming);
  var motionBlur = options.motionBlur !== undefined ? options.motionBlur : r.motionBlur;
  var mbPxRatio = r.motionBlurPxRatio;
  var hasCompoundNodes = cy.hasCompoundNodes();
  var inNodeDragGesture = r.hoverData.draggingEles;
  var inBoxSelection = r.hoverData.selecting || r.touchData.selecting ? true : false;
  motionBlur = motionBlur && !forcedContext && r.motionBlurEnabled && !inBoxSelection;
  var motionBlurFadeEffect = motionBlur;
  if (!forcedContext) {
    if (r.prevPxRatio !== pixelRatio) {
      r.invalidateContainerClientCoordsCache();
      r.matchCanvasSize(r.container);
      r.redrawHint('eles', true);
      r.redrawHint('drag', true);
    }
    r.prevPxRatio = pixelRatio;
  }
  if (!forcedContext && r.motionBlurTimeout) {
    clearTimeout(r.motionBlurTimeout);
  }
  if (motionBlur) {
    if (r.mbFrames == null) {
      r.mbFrames = 0;
    }
    r.mbFrames++;
    if (r.mbFrames < 3) {
      // need several frames before even high quality motionblur
      motionBlurFadeEffect = false;
    }

    // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)
    if (r.mbFrames > r.minMbLowQualFrames) {
      //r.fullQualityMb = false;
      r.motionBlurPxRatio = r.mbPxRBlurry;
    }
  }
  if (r.clearingMotionBlur) {
    r.motionBlurPxRatio = 1;
  }

  // b/c drawToContext() may be async w.r.t. redraw(), keep track of last texture frame
  // because a rogue async texture frame would clear needDraw
  if (r.textureDrawLastFrame && !textureDraw) {
    needDraw[r.NODE] = true;
    needDraw[r.SELECT_BOX] = true;
  }
  var style = cy.style();
  var zoom = cy.zoom();
  var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;
  var pan = cy.pan();
  var effectivePan = {
    x: pan.x,
    y: pan.y
  };
  var vp = {
    zoom: zoom,
    pan: {
      x: pan.x,
      y: pan.y
    }
  };
  var prevVp = r.prevViewport;
  var viewportIsDiff = prevVp === undefined || vp.zoom !== prevVp.zoom || vp.pan.x !== prevVp.pan.x || vp.pan.y !== prevVp.pan.y;

  // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)
  if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {
    r.motionBlurPxRatio = 1;
  }
  if (forcedPan) {
    effectivePan = forcedPan;
  }

  // apply pixel ratio

  effectiveZoom *= pixelRatio;
  effectivePan.x *= pixelRatio;
  effectivePan.y *= pixelRatio;
  var eles = r.getCachedZSortedEles();
  function mbclear(context, x, y, w, h) {
    var gco = context.globalCompositeOperation;
    context.globalCompositeOperation = 'destination-out';
    r.colorFillStyle(context, 255, 255, 255, r.motionBlurTransparency);
    context.fillRect(x, y, w, h);
    context.globalCompositeOperation = gco;
  }
  function setContextTransform(context, clear) {
    var ePan, eZoom, w, h;
    if (!r.clearingMotionBlur && (context === data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] || context === data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG])) {
      ePan = {
        x: pan.x * mbPxRatio,
        y: pan.y * mbPxRatio
      };
      eZoom = zoom * mbPxRatio;
      w = r.canvasWidth * mbPxRatio;
      h = r.canvasHeight * mbPxRatio;
    } else {
      ePan = effectivePan;
      eZoom = effectiveZoom;
      w = r.canvasWidth;
      h = r.canvasHeight;
    }
    context.setTransform(1, 0, 0, 1, 0, 0);
    if (clear === 'motionBlur') {
      mbclear(context, 0, 0, w, h);
    } else if (!forcedContext && (clear === undefined || clear)) {
      context.clearRect(0, 0, w, h);
    }
    if (!drawAllLayers) {
      context.translate(ePan.x, ePan.y);
      context.scale(eZoom, eZoom);
    }
    if (forcedPan) {
      context.translate(forcedPan.x, forcedPan.y);
    }
    if (forcedZoom) {
      context.scale(forcedZoom, forcedZoom);
    }
  }
  if (!textureDraw) {
    r.textureDrawLastFrame = false;
  }
  if (textureDraw) {
    r.textureDrawLastFrame = true;
    if (!r.textureCache) {
      r.textureCache = {};
      r.textureCache.bb = cy.mutableElements().boundingBox();
      r.textureCache.texture = r.data.bufferCanvases[r.TEXTURE_BUFFER];
      var cxt = r.data.bufferContexts[r.TEXTURE_BUFFER];
      cxt.setTransform(1, 0, 0, 1, 0, 0);
      cxt.clearRect(0, 0, r.canvasWidth * r.textureMult, r.canvasHeight * r.textureMult);
      r.render({
        forcedContext: cxt,
        drawOnlyNodeLayer: true,
        forcedPxRatio: pixelRatio * r.textureMult
      });
      var vp = r.textureCache.viewport = {
        zoom: cy.zoom(),
        pan: cy.pan(),
        width: r.canvasWidth,
        height: r.canvasHeight
      };
      vp.mpan = {
        x: (0 - vp.pan.x) / vp.zoom,
        y: (0 - vp.pan.y) / vp.zoom
      };
    }
    needDraw[r.DRAG] = false;
    needDraw[r.NODE] = false;
    var context = data.contexts[r.NODE];
    var texture = r.textureCache.texture;
    var vp = r.textureCache.viewport;
    context.setTransform(1, 0, 0, 1, 0, 0);
    if (motionBlur) {
      mbclear(context, 0, 0, vp.width, vp.height);
    } else {
      context.clearRect(0, 0, vp.width, vp.height);
    }
    var outsideBgColor = style.core('outside-texture-bg-color').value;
    var outsideBgOpacity = style.core('outside-texture-bg-opacity').value;
    r.colorFillStyle(context, outsideBgColor[0], outsideBgColor[1], outsideBgColor[2], outsideBgOpacity);
    context.fillRect(0, 0, vp.width, vp.height);
    var zoom = cy.zoom();
    setContextTransform(context, false);
    context.clearRect(vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
    context.drawImage(texture, vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  } else if (r.textureOnViewport && !forcedContext) {
    // clear the cache since we don't need it
    r.textureCache = null;
  }
  var extent = cy.extent();
  var vpManip = r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming || r.hoverData.draggingEles || r.cy.animated();
  var hideEdges = r.hideEdgesOnViewport && vpManip;
  var needMbClear = [];
  needMbClear[r.NODE] = !needDraw[r.NODE] && motionBlur && !r.clearedForMotionBlur[r.NODE] || r.clearingMotionBlur;
  if (needMbClear[r.NODE]) {
    r.clearedForMotionBlur[r.NODE] = true;
  }
  needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;
  if (needMbClear[r.DRAG]) {
    r.clearedForMotionBlur[r.DRAG] = true;
  }
  if (needDraw[r.NODE] || drawAllLayers || drawOnlyNodeLayer || needMbClear[r.NODE]) {
    var useBuffer = motionBlur && !needMbClear[r.NODE] && mbPxRatio !== 1;
    var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] : data.contexts[r.NODE]);
    var clear = motionBlur && !useBuffer ? 'motionBlur' : undefined;
    setContextTransform(context, clear);
    if (hideEdges) {
      r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);
    } else {
      r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);
    }
    if (r.debug) {
      r.drawDebugPoints(context, eles.nondrag);
    }
    if (!drawAllLayers && !motionBlur) {
      needDraw[r.NODE] = false;
    }
  }
  if (!drawOnlyNodeLayer && (needDraw[r.DRAG] || drawAllLayers || needMbClear[r.DRAG])) {
    var useBuffer = motionBlur && !needMbClear[r.DRAG] && mbPxRatio !== 1;
    var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG] : data.contexts[r.DRAG]);
    setContextTransform(context, motionBlur && !useBuffer ? 'motionBlur' : undefined);
    if (hideEdges) {
      r.drawCachedNodes(context, eles.drag, pixelRatio, extent);
    } else {
      r.drawCachedElements(context, eles.drag, pixelRatio, extent);
    }
    if (r.debug) {
      r.drawDebugPoints(context, eles.drag);
    }
    if (!drawAllLayers && !motionBlur) {
      needDraw[r.DRAG] = false;
    }
  }
  this.drawSelectionRectangle(options, setContextTransform);

  // motionblur: blit rendered blurry frames
  if (motionBlur && mbPxRatio !== 1) {
    var cxtNode = data.contexts[r.NODE];
    var txtNode = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE];
    var cxtDrag = data.contexts[r.DRAG];
    var txtDrag = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG];
    var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {
      cxt.setTransform(1, 0, 0, 1, 0, 0);
      if (needClear || !motionBlurFadeEffect) {
        cxt.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
      } else {
        mbclear(cxt, 0, 0, r.canvasWidth, r.canvasHeight);
      }
      var pxr = mbPxRatio;
      cxt.drawImage(txt,
      // img
      0, 0,
      // sx, sy
      r.canvasWidth * pxr, r.canvasHeight * pxr,
      // sw, sh
      0, 0,
      // x, y
      r.canvasWidth, r.canvasHeight // w, h
      );
    };
    if (needDraw[r.NODE] || needMbClear[r.NODE]) {
      drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);
      needDraw[r.NODE] = false;
    }
    if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {
      drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);
      needDraw[r.DRAG] = false;
    }
  }
  r.prevViewport = vp;
  if (r.clearingMotionBlur) {
    r.clearingMotionBlur = false;
    r.motionBlurCleared = true;
    r.motionBlur = true;
  }
  if (motionBlur) {
    r.motionBlurTimeout = setTimeout(function () {
      r.motionBlurTimeout = null;
      r.clearedForMotionBlur[r.NODE] = false;
      r.clearedForMotionBlur[r.DRAG] = false;
      r.motionBlur = false;
      r.clearingMotionBlur = !textureDraw;
      r.mbFrames = 0;
      needDraw[r.NODE] = true;
      needDraw[r.DRAG] = true;
      r.redraw();
    }, motionBlurDelay);
  }
  if (!forcedContext) {
    cy.emit('render');
  }
};
var fpsHeight;
CRp$5.drawSelectionRectangle = function (options, setContextTransform) {
  var r = this;
  var cy = r.cy;
  var data = r.data;
  var style = cy.style();
  var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  var drawAllLayers = options.drawAllLayers;
  var needDraw = data.canvasNeedsRedraw;
  var forcedContext = options.forcedContext;
  if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {
    var context = forcedContext || data.contexts[r.SELECT_BOX];
    setContextTransform(context);
    if (r.selection[4] == 1 && (r.hoverData.selecting || r.touchData.selecting)) {
      var zoom = r.cy.zoom();
      var borderWidth = style.core('selection-box-border-width').value / zoom;
      context.lineWidth = borderWidth;
      context.fillStyle = 'rgba(' + style.core('selection-box-color').value[0] + ',' + style.core('selection-box-color').value[1] + ',' + style.core('selection-box-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';
      context.fillRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
      if (borderWidth > 0) {
        context.strokeStyle = 'rgba(' + style.core('selection-box-border-color').value[0] + ',' + style.core('selection-box-border-color').value[1] + ',' + style.core('selection-box-border-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';
        context.strokeRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
      }
    }
    if (data.bgActivePosistion && !r.hoverData.selecting) {
      var zoom = r.cy.zoom();
      var pos = data.bgActivePosistion;
      context.fillStyle = 'rgba(' + style.core('active-bg-color').value[0] + ',' + style.core('active-bg-color').value[1] + ',' + style.core('active-bg-color').value[2] + ',' + style.core('active-bg-opacity').value + ')';
      context.beginPath();
      context.arc(pos.x, pos.y, style.core('active-bg-size').pfValue / zoom, 0, 2 * Math.PI);
      context.fill();
    }
    var timeToRender = r.lastRedrawTime;
    if (r.showFps && timeToRender) {
      timeToRender = Math.round(timeToRender);
      var fps = Math.round(1000 / timeToRender);
      var text = '1 frame = ' + timeToRender + ' ms = ' + fps + ' fps';
      context.setTransform(1, 0, 0, 1, 0, 0);
      context.fillStyle = 'rgba(255, 0, 0, 0.75)';
      context.strokeStyle = 'rgba(255, 0, 0, 0.75)';
      // context.lineWidth = 1;
      context.font = '30px Arial';
      if (!fpsHeight) {
        var dims = context.measureText(text);
        fpsHeight = dims.actualBoundingBoxAscent;
      }
      context.fillText(text, 0, fpsHeight);
      var maxFps = 60;
      context.strokeRect(0, fpsHeight + 10, 250, 20);
      context.fillRect(0, fpsHeight + 10, 250 * Math.min(fps / maxFps, 1), 20);
    }
    if (!drawAllLayers) {
      needDraw[r.SELECT_BOX] = false;
    }
  }
};

/**
 * Notes:
 * - All colors have premultiplied alpha. Very important for textues and 
 *   blending to work correctly.
 */

function compileShader(gl, type, source) {
  var shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    throw new Error(gl.getShaderInfoLog(shader));
  }
  // console.log(gl.getShaderInfoLog(shader));
  return shader;
}
function createProgram(gl, vertexSource, fragementSource) {
  var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);
  var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragementSource);
  var program = gl.createProgram();
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);
  gl.linkProgram(program);
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    throw new Error('Could not initialize shaders');
  }
  return program;
}

/**
 * Creates an offscren canvas with a 2D context, for the
 * canvas renderer to use for drawing textures.
 */
function createTextureCanvas(r, width, height) {
  if (height === undefined) {
    height = width;
  }
  var canvas = r.makeOffscreenCanvas(width, height);
  var ctx = canvas.context = canvas.getContext('2d');
  canvas.clear = function () {
    return ctx.clearRect(0, 0, canvas.width, canvas.height);
  };
  canvas.clear();
  return canvas;
}

/**
 * Returns the current pan & zoom values, scaled by the pixel ratio.
 */
function getEffectivePanZoom(r) {
  var pixelRatio = r.pixelRatio;
  var zoom = r.cy.zoom();
  var pan = r.cy.pan();
  return {
    zoom: zoom * pixelRatio,
    pan: {
      x: pan.x * pixelRatio,
      y: pan.y * pixelRatio
    }
  };
}

/**
 * Returns the zoom value, scaled by the pixel ratio.
 */
function getEffectiveZoom(r) {
  var pixelRatio = r.pixelRatio;
  var zoom = r.cy.zoom();
  return zoom * pixelRatio;
}
function modelToRenderedPosition(r, pan, zoom, x, y) {
  var rx = x * zoom + pan.x;
  var ry = y * zoom + pan.y;
  ry = Math.round(r.canvasHeight - ry); // adjust for webgl
  return [rx, ry];
}
function isSimpleShape(node) {
  // the actual shape is checked in ElementDrawingWebGL._getVertTypeForShape()
  // no need to check it twice, this just checks other visual properties
  if (node.pstyle('background-fill').value !== 'solid') return false;
  if (node.pstyle('background-image').strValue !== 'none') return false;
  if (node.pstyle('border-width').value === 0) return true;
  if (node.pstyle('border-opacity').value === 0) return true;
  // we have a border but it must be simple
  if (node.pstyle('border-style').value !== 'solid') return false;
  // TODO ignoring 'border-cap', 'border-join' and 'border-position' for now
  return true;
}
function arrayEqual(a1, a2) {
  if (a1.length !== a2.length) {
    return false;
  }
  for (var i = 0; i < a1.length; i++) {
    if (a1[i] !== a2[i]) {
      return false;
    }
  }
  return true;
}

/**
 * Takes color & opacity style values and converts them to WebGL format. 
 * Alpha is premultiplied.
 */
function toWebGLColor(color, opacity, outArray) {
  var r = color[0] / 255;
  var g = color[1] / 255;
  var b = color[2] / 255;
  var a = opacity;
  var arr = outArray || new Array(4);
  arr[0] = r * a;
  arr[1] = g * a;
  arr[2] = b * a;
  arr[3] = a;
  return arr;
}
function indexToVec4(index, outArray) {
  var arr = outArray || new Array(4);
  arr[0] = (index >> 0 & 0xFF) / 0xFF;
  arr[1] = (index >> 8 & 0xFF) / 0xFF;
  arr[2] = (index >> 16 & 0xFF) / 0xFF;
  arr[3] = (index >> 24 & 0xFF) / 0xFF;
  return arr;
}
function vec4ToIndex(vec4) {
  return vec4[0] + (vec4[1] << 8) + (vec4[2] << 16) + (vec4[3] << 24);
}
function createTexture(gl, debugID) {
  var texture = gl.createTexture();
  texture.buffer = function (offscreenCanvas) {
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);

    // very important, this tells webgl to premultiply colors by the alpha channel
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offscreenCanvas);
    gl.generateMipmap(gl.TEXTURE_2D);
    gl.bindTexture(gl.TEXTURE_2D, null);
  };
  texture.deleteTexture = function () {
    gl.deleteTexture(texture);
  };
  return texture;
}
function getTypeInfo(gl, glslType) {
  switch (glslType) {
    case 'float':
      return [1, gl.FLOAT, 4];
    case 'vec2':
      return [2, gl.FLOAT, 4];
    case 'vec3':
      return [3, gl.FLOAT, 4];
    case 'vec4':
      return [4, gl.FLOAT, 4];
    case 'int':
      return [1, gl.INT, 4];
    case 'ivec2':
      return [2, gl.INT, 4];
  }
}
function createTypedArray(gl, glType, dataOrSize) {
  switch (glType) {
    case gl.FLOAT:
      return new Float32Array(dataOrSize);
    case gl.INT:
      return new Int32Array(dataOrSize);
  }
}
function createTypedArrayView(gl, glType, array, stride, size, i) {
  switch (glType) {
    case gl.FLOAT:
      return new Float32Array(array.buffer, i * stride, size);
    case gl.INT:
      return new Int32Array(array.buffer, i * stride, size);
  }
}

/** @param {WebGLRenderingContext} gl */
function createBufferStaticDraw(gl, type, attributeLoc, dataArray) {
  var _getTypeInfo = getTypeInfo(gl, type),
    _getTypeInfo2 = _slicedToArray(_getTypeInfo, 2),
    size = _getTypeInfo2[0],
    glType = _getTypeInfo2[1];
  var data = createTypedArray(gl, glType, dataArray);
  var buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
  if (glType === gl.FLOAT) {
    gl.vertexAttribPointer(attributeLoc, size, glType, false, 0, 0);
  } else if (glType === gl.INT) {
    gl.vertexAttribIPointer(attributeLoc, size, glType, 0, 0);
  }
  gl.enableVertexAttribArray(attributeLoc);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);
  return buffer;
}

/** 
 * Creates a float buffer with gl.DYNAMIC_DRAW.
 * The returned buffer object contains functions to easily set instance data and buffer the data before a draw call.
 * @param {WebGLRenderingContext} gl 
 */
function createBufferDynamicDraw(gl, instances, type, attributeLoc) {
  var _getTypeInfo3 = getTypeInfo(gl, type),
    _getTypeInfo4 = _slicedToArray(_getTypeInfo3, 3),
    size = _getTypeInfo4[0],
    glType = _getTypeInfo4[1],
    bytes = _getTypeInfo4[2];
  var dataArray = createTypedArray(gl, glType, instances * size);
  var stride = size * bytes;
  var buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, instances * stride, gl.DYNAMIC_DRAW);
  gl.enableVertexAttribArray(attributeLoc);
  if (glType === gl.FLOAT) {
    gl.vertexAttribPointer(attributeLoc, size, glType, false, stride, 0);
  } else if (glType === gl.INT) {
    gl.vertexAttribIPointer(attributeLoc, size, glType, stride, 0);
  }
  gl.vertexAttribDivisor(attributeLoc, 1);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  // use array views to set values directly into the buffer array
  var views = new Array(instances);
  for (var i = 0; i < instances; i++) {
    views[i] = createTypedArrayView(gl, glType, dataArray, stride, size, i);
  }
  buffer.dataArray = dataArray;
  buffer.stride = stride;
  buffer.size = size;
  buffer.getView = function (i) {
    return views[i];
  };
  buffer.setPoint = function (i, x, y) {
    var view = views[i];
    view[0] = x;
    view[1] = y;
  };
  buffer.bufferSubData = function (count) {
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    if (count) {
      gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray, 0, count * size);
    } else {
      gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray);
    }
  };
  return buffer;
}

/** 
 * Creates a buffer of 3x3 matrix data for use as attribute data.
 * @param {WebGLRenderingContext} gl 
 */
function create3x3MatrixBufferDynamicDraw(gl, instances, attributeLoc) {
  var matrixSize = 9; // 3x3 matrix
  var matrixData = new Float32Array(instances * matrixSize);

  // use matrix views to set values directly into the matrixData array
  var matrixViews = new Array(instances);
  for (var i = 0; i < instances; i++) {
    var byteOffset = i * matrixSize * 4; // 4 bytes per float
    matrixViews[i] = new Float32Array(matrixData.buffer, byteOffset, matrixSize); // array view
  }
  var buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, matrixData.byteLength, gl.DYNAMIC_DRAW);

  // each row of the matrix needs to be a separate attribute
  for (var _i = 0; _i < 3; _i++) {
    var loc = attributeLoc + _i;
    gl.enableVertexAttribArray(loc);
    gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 3 * 12, _i * 12);
    gl.vertexAttribDivisor(loc, 1);
  }
  gl.bindBuffer(gl.ARRAY_BUFFER, null);
  buffer.getMatrixView = function (i) {
    return matrixViews[i];
  };

  // TODO this is too slow, use getMatrixView and pass the view directly to the glmatrix library
  buffer.setData = function (matrix, i) {
    matrixViews[i].set(matrix, 0);
  };
  buffer.bufferSubData = function () {
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferSubData(gl.ARRAY_BUFFER, 0, matrixData);
  };
  return buffer;
}

/** 
 * Creates a Frame Buffer to use for offscreen rendering.
 * @param {WebGLRenderingContext} gl 
 */
function createPickingFrameBuffer(gl) {
  // Create and bind the framebuffer
  var fb = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, fb);

  // Create a texture to render to
  var targetTexture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  // attach the texture as the first color attachment
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  fb.setFramebufferAttachmentSizes = function (width, height) {
    gl.bindTexture(gl.TEXTURE_2D, targetTexture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  };
  return fb;
}

/**
 * Common utilities
 * @module glMatrix
 */
// Configuration Constants
var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
if (!Math.hypot) Math.hypot = function () {
  var y = 0,
      i = arguments.length;

  while (i--) {
    y += arguments[i] * arguments[i];
  }

  return Math.sqrt(y);
};

/**
 * 3x3 Matrix
 * @module mat3
 */

/**
 * Creates a new identity mat3
 *
 * @returns {mat3} a new 3x3 matrix
 */

function create() {
  var out = new ARRAY_TYPE(9);

  if (ARRAY_TYPE != Float32Array) {
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[5] = 0;
    out[6] = 0;
    out[7] = 0;
  }

  out[0] = 1;
  out[4] = 1;
  out[8] = 1;
  return out;
}
/**
 * Set a mat3 to the identity matrix
 *
 * @param {mat3} out the receiving matrix
 * @returns {mat3} out
 */

function identity(out) {
  out[0] = 1;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = 1;
  out[5] = 0;
  out[6] = 0;
  out[7] = 0;
  out[8] = 1;
  return out;
}
/**
 * Multiplies two mat3's
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the first operand
 * @param {ReadonlyMat3} b the second operand
 * @returns {mat3} out
 */

function multiply(out, a, b) {
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2];
  var a10 = a[3],
      a11 = a[4],
      a12 = a[5];
  var a20 = a[6],
      a21 = a[7],
      a22 = a[8];
  var b00 = b[0],
      b01 = b[1],
      b02 = b[2];
  var b10 = b[3],
      b11 = b[4],
      b12 = b[5];
  var b20 = b[6],
      b21 = b[7],
      b22 = b[8];
  out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  return out;
}
/**
 * Translate a mat3 by the given vector
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to translate
 * @param {ReadonlyVec2} v vector to translate by
 * @returns {mat3} out
 */

function translate(out, a, v) {
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2],
      a10 = a[3],
      a11 = a[4],
      a12 = a[5],
      a20 = a[6],
      a21 = a[7],
      a22 = a[8],
      x = v[0],
      y = v[1];
  out[0] = a00;
  out[1] = a01;
  out[2] = a02;
  out[3] = a10;
  out[4] = a11;
  out[5] = a12;
  out[6] = x * a00 + y * a10 + a20;
  out[7] = x * a01 + y * a11 + a21;
  out[8] = x * a02 + y * a12 + a22;
  return out;
}
/**
 * Rotates a mat3 by the given angle
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to rotate
 * @param {Number} rad the angle to rotate the matrix by
 * @returns {mat3} out
 */

function rotate(out, a, rad) {
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2],
      a10 = a[3],
      a11 = a[4],
      a12 = a[5],
      a20 = a[6],
      a21 = a[7],
      a22 = a[8],
      s = Math.sin(rad),
      c = Math.cos(rad);
  out[0] = c * a00 + s * a10;
  out[1] = c * a01 + s * a11;
  out[2] = c * a02 + s * a12;
  out[3] = c * a10 - s * a00;
  out[4] = c * a11 - s * a01;
  out[5] = c * a12 - s * a02;
  out[6] = a20;
  out[7] = a21;
  out[8] = a22;
  return out;
}
/**
 * Scales the mat3 by the dimensions in the given vec2
 *
 * @param {mat3} out the receiving matrix
 * @param {ReadonlyMat3} a the matrix to rotate
 * @param {ReadonlyVec2} v the vec2 to scale the matrix by
 * @returns {mat3} out
 **/

function scale(out, a, v) {
  var x = v[0],
      y = v[1];
  out[0] = x * a[0];
  out[1] = x * a[1];
  out[2] = x * a[2];
  out[3] = y * a[3];
  out[4] = y * a[4];
  out[5] = y * a[5];
  out[6] = a[6];
  out[7] = a[7];
  out[8] = a[8];
  return out;
}
/**
 * Generates a 2D projection matrix with the given bounds
 *
 * @param {mat3} out mat3 frustum matrix will be written into
 * @param {number} width Width of your gl context
 * @param {number} height Height of gl context
 * @returns {mat3} out
 */

function projection(out, width, height) {
  out[0] = 2 / width;
  out[1] = 0;
  out[2] = 0;
  out[3] = 0;
  out[4] = -2 / height;
  out[5] = 0;
  out[6] = -1;
  out[7] = 1;
  out[8] = 1;
  return out;
}

// A "texture atlas" is a big canvas, and sections of it are used as textures for nodes/labels.

/**
 * A single square texture atlas (also known as a "sprite sheet").
 */
var Atlas = /*#__PURE__*/function () {
  function Atlas(r, texSize, texRows, createTextureCanvas) {
    _classCallCheck(this, Atlas);
    this.debugID = Math.floor(Math.random() * 10000);
    this.r = r;
    this.texSize = texSize;
    this.texRows = texRows;
    this.texHeight = Math.floor(texSize / texRows);
    this.enableWrapping = true; // hardcoded for now, can be made an option

    this.locked = false; // once an atlas is locked it can no longer be drawn to
    this.texture = null; // WebGLTexture object
    this.needsBuffer = true;

    // a "location" is an pointer into the atlas with a 'row' and 'x' fields
    this.freePointer = {
      x: 0,
      row: 0
    };

    // map from the style key to the row/x where the texture starts
    // if the texture wraps then there's a second location
    this.keyToLocation = new Map(); // styleKey -> [ location, location ]

    this.canvas = createTextureCanvas(r, texSize, texSize);
    this.scratch = createTextureCanvas(r, texSize, this.texHeight, 'scratch');
  }
  return _createClass(Atlas, [{
    key: "lock",
    value: function lock() {
      this.locked = true;
    }
  }, {
    key: "getKeys",
    value: function getKeys() {
      return new Set(this.keyToLocation.keys());
    }
  }, {
    key: "getScale",
    value: function getScale(_ref) {
      var w = _ref.w,
        h = _ref.h;
      var texHeight = this.texHeight,
        maxTexWidth = this.texSize;
      // try to fit to the height of a row
      var scale = texHeight / h; // TODO what about pixelRatio?
      var texW = w * scale;
      var texH = h * scale;
      // if the scaled width is too wide then scale to fit max width instead
      if (texW > maxTexWidth) {
        scale = maxTexWidth / w;
        texW = w * scale;
        texH = h * scale;
      }
      return {
        scale: scale,
        texW: texW,
        texH: texH
      };
    }
  }, {
    key: "draw",
    value: function draw(key, bb, doDrawing) {
      var _this = this;
      if (this.locked) throw new Error('can\'t draw, atlas is locked');
      var texSize = this.texSize,
        texRows = this.texRows,
        texHeight = this.texHeight;
      var _this$getScale = this.getScale(bb),
        scale = _this$getScale.scale,
        texW = _this$getScale.texW,
        texH = _this$getScale.texH;
      var drawAt = function drawAt(location, canvas) {
        if (doDrawing && canvas) {
          var context = canvas.context;
          var x = location.x,
            row = location.row;
          var xOffset = x;
          var yOffset = texHeight * row;
          context.save();
          context.translate(xOffset, yOffset);
          context.scale(scale, scale);
          doDrawing(context, bb);
          context.restore();
        }
      };
      var locations = [null, null];
      var drawNormal = function drawNormal() {
        // don't need to wrap, draw directly on the canvas
        drawAt(_this.freePointer, _this.canvas);
        locations[0] = {
          x: _this.freePointer.x,
          y: _this.freePointer.row * texHeight,
          w: texW,
          h: texH
        };
        locations[1] = {
          // create a second location with a width of 0, for convenience
          x: _this.freePointer.x + texW,
          y: _this.freePointer.row * texHeight,
          w: 0,
          h: texH
        };

        // move the pointer to the end of the texture
        _this.freePointer.x += texW;
        if (_this.freePointer.x == texSize) {
          _this.freePointer.x = 0;
          _this.freePointer.row++;
        }
      };
      var drawWrapped = function drawWrapped() {
        var scratch = _this.scratch,
          canvas = _this.canvas;

        // Draw to the scratch canvas
        scratch.clear();
        drawAt({
          x: 0,
          row: 0
        }, scratch);
        var firstTexW = texSize - _this.freePointer.x;
        var secondTexW = texW - firstTexW;
        var h = texHeight;
        {
          // copy first part of scratch to the first texture
          var dx = _this.freePointer.x;
          var dy = _this.freePointer.row * texHeight;
          var w = firstTexW;
          canvas.context.drawImage(scratch, 0, 0, w, h, dx, dy, w, h);
          locations[0] = {
            x: dx,
            y: dy,
            w: w,
            h: texH
          };
        }
        {
          // copy second part of scratch to the second texture
          var sx = firstTexW;
          var _dy = (_this.freePointer.row + 1) * texHeight;
          var _w = secondTexW;
          if (canvas) {
            canvas.context.drawImage(scratch, sx, 0, _w, h, 0, _dy, _w, h);
          }
          locations[1] = {
            x: 0,
            y: _dy,
            w: _w,
            h: texH
          };
        }
        _this.freePointer.x = secondTexW;
        _this.freePointer.row++;
      };
      var moveToStartOfNextRow = function moveToStartOfNextRow() {
        _this.freePointer.x = 0;
        _this.freePointer.row++;
      };
      if (this.freePointer.x + texW <= texSize) {
        // There's enough space in the current row
        drawNormal();
      } else if (this.freePointer.row >= texRows - 1) {
        // Need to move to the next row, but there are no more rows, atlas is full.
        return false;
      } else if (this.freePointer.x === texSize) {
        // happen to be right at end of current row
        moveToStartOfNextRow();
        drawNormal();
      } else if (this.enableWrapping) {
        // draw part of the texture to the end of the curent row, then wrap to the next row
        drawWrapped();
      } else {
        // move to the start of the next row, then draw normally
        moveToStartOfNextRow();
        drawNormal();
      }
      this.keyToLocation.set(key, locations);
      this.needsBuffer = true;
      return locations;
    }
  }, {
    key: "getOffsets",
    value: function getOffsets(key) {
      return this.keyToLocation.get(key);
    }
  }, {
    key: "isEmpty",
    value: function isEmpty() {
      return this.freePointer.x === 0 && this.freePointer.row === 0;
    }
  }, {
    key: "canFit",
    value: function canFit(bb) {
      if (this.locked) return false;
      var texSize = this.texSize,
        texRows = this.texRows;
      var _this$getScale2 = this.getScale(bb),
        texW = _this$getScale2.texW;
      if (this.freePointer.x + texW > texSize) {
        // need to wrap
        return this.freePointer.row < texRows - 1; // return true if there's a row to wrap to
      }
      return true;
    }

    // called on every frame
  }, {
    key: "bufferIfNeeded",
    value: function bufferIfNeeded(gl) {
      if (!this.texture) {
        this.texture = createTexture(gl, this.debugID);
      }
      if (this.needsBuffer) {
        this.texture.buffer(this.canvas);
        this.needsBuffer = false;
        if (this.locked) {
          this.canvas = null;
          this.scratch = null;
        }
      }
    }
  }, {
    key: "dispose",
    value: function dispose() {
      if (this.texture) {
        this.texture.deleteTexture();
        this.texture = null;
      }
      this.canvas = null;
      this.scratch = null;
      this.locked = true;
    }
  }]);
}();

/**
 * A collection of texture atlases, all of the same "render type". 
 * ('node-body' is an example of a render type.)
 * An AtlasCollection can also be notified when a texture is no longer needed, 
 * and it can garbage collect the unused textures.
 */
var AtlasCollection = /*#__PURE__*/function () {
  function AtlasCollection(r, texSize, texRows, createTextureCanvas) {
    _classCallCheck(this, AtlasCollection);
    this.r = r;
    this.texSize = texSize;
    this.texRows = texRows;
    this.createTextureCanvas = createTextureCanvas;
    this.atlases = [];
    this.styleKeyToAtlas = new Map();
    this.markedKeys = new Set(); // marked for garbage collection
  }
  return _createClass(AtlasCollection, [{
    key: "getKeys",
    value: function getKeys() {
      return new Set(this.styleKeyToAtlas.keys());
    }
  }, {
    key: "_createAtlas",
    value: function _createAtlas() {
      var r = this.r,
        texSize = this.texSize,
        texRows = this.texRows,
        createTextureCanvas = this.createTextureCanvas;
      return new Atlas(r, texSize, texRows, createTextureCanvas);
    }
  }, {
    key: "_getScratchCanvas",
    value: function _getScratchCanvas() {
      if (!this.scratch) {
        var r = this.r,
          texSize = this.texSize,
          texRows = this.texRows,
          createTextureCanvas = this.createTextureCanvas;
        var texHeight = Math.floor(texSize / texRows);
        this.scratch = createTextureCanvas(r, texSize, texHeight, 'scratch');
      }
      return this.scratch;
    }
  }, {
    key: "draw",
    value: function draw(key, bb, doDrawing) {
      var atlas = this.styleKeyToAtlas.get(key);
      if (!atlas) {
        // check for space at the end of the last atlas
        atlas = this.atlases[this.atlases.length - 1];
        if (!atlas || !atlas.canFit(bb)) {
          if (atlas) atlas.lock();
          // create a new atlas
          atlas = this._createAtlas();
          this.atlases.push(atlas);
        }
        atlas.draw(key, bb, doDrawing);
        this.styleKeyToAtlas.set(key, atlas);
      }
      return atlas;
    }
  }, {
    key: "getAtlas",
    value: function getAtlas(key) {
      return this.styleKeyToAtlas.get(key);
    }
  }, {
    key: "hasAtlas",
    value: function hasAtlas(key) {
      return this.styleKeyToAtlas.has(key);
    }
  }, {
    key: "markKeyForGC",
    value: function markKeyForGC(key) {
      this.markedKeys.add(key);
    }
  }, {
    key: "gc",
    value: function gc() {
      var _this2 = this;
      var markedKeys = this.markedKeys;
      if (markedKeys.size === 0) {
        console.log('nothing to garbage collect');
        return;
      }
      var newAtlases = [];
      var newStyleKeyToAtlas = new Map();
      var newAtlas = null;
      var _iterator = _createForOfIteratorHelper(this.atlases),
        _step;
      try {
        var _loop = function _loop() {
          var atlas = _step.value;
          var keys = atlas.getKeys();
          var keysToCollect = intersection(markedKeys, keys);
          if (keysToCollect.size === 0) {
            // this atlas can still be used
            newAtlases.push(atlas);
            keys.forEach(function (k) {
              return newStyleKeyToAtlas.set(k, atlas);
            });
            return 1; // continue
          }
          if (!newAtlas) {
            newAtlas = _this2._createAtlas();
            newAtlases.push(newAtlas);
          }
          var _iterator2 = _createForOfIteratorHelper(keys),
            _step2;
          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var key = _step2.value;
              if (!keysToCollect.has(key)) {
                var _atlas$getOffsets = atlas.getOffsets(key),
                  _atlas$getOffsets2 = _slicedToArray(_atlas$getOffsets, 2),
                  s1 = _atlas$getOffsets2[0],
                  s2 = _atlas$getOffsets2[1];
                if (!newAtlas.canFit({
                  w: s1.w + s2.w,
                  h: s1.h
                })) {
                  newAtlas.lock();
                  newAtlas = _this2._createAtlas();
                  newAtlases.push(newAtlas);
                }
                if (atlas.canvas) {
                  // if the texture can't be copied then it will have to be redrawn on the next frame
                  _this2._copyTextureToNewAtlas(key, atlas, newAtlas);
                  newStyleKeyToAtlas.set(key, newAtlas);
                }
              }
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }
          atlas.dispose();
        };
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          if (_loop()) continue;
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      this.atlases = newAtlases;
      this.styleKeyToAtlas = newStyleKeyToAtlas;
      this.markedKeys = new Set();
    }
  }, {
    key: "_copyTextureToNewAtlas",
    value: function _copyTextureToNewAtlas(key, oldAtlas, newAtlas) {
      var _oldAtlas$getOffsets = oldAtlas.getOffsets(key),
        _oldAtlas$getOffsets2 = _slicedToArray(_oldAtlas$getOffsets, 2),
        s1 = _oldAtlas$getOffsets2[0],
        s2 = _oldAtlas$getOffsets2[1];
      if (s2.w === 0) {
        // the texture does not wrap, draw directly to new atlas
        newAtlas.draw(key, s1, function (context) {
          context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
        });
      } else {
        // the texture wraps, first draw both parts to a scratch canvas
        var scratch = this._getScratchCanvas();
        scratch.clear();
        scratch.context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
        scratch.context.drawImage(oldAtlas.canvas, s2.x, s2.y, s2.w, s2.h, s1.w, 0, s2.w, s2.h);

        // now draw the scratch to the new atlas
        var w = s1.w + s2.w;
        var h = s1.h;
        newAtlas.draw(key, {
          w: w,
          h: h
        }, function (context) {
          context.drawImage(scratch, 0, 0, w, h, 0, 0, w, h // the destination context has already been translated to the correct position
          );
        });
      }
    }
  }, {
    key: "getCounts",
    value: function getCounts() {
      return {
        keyCount: this.styleKeyToAtlas.size,
        atlasCount: new Set(this.styleKeyToAtlas.values()).size
      };
    }
  }]);
}();
function intersection(set1, set2) {
  // TODO why no Set.intersection in node 16???
  if (set1.intersection) return set1.intersection(set2);else return new Set(_toConsumableArray(set1).filter(function (x) {
    return set2.has(x);
  }));
}

/**
 * Used to manage batches of Atlases for drawing nodes and labels.
 * Supports different types of AtlasCollections for different render types,
 * for example 'node-body' and 'node-label' would be different render types.
 * Render types are kept separate because they will likely need to be garbage collected
 * separately and its not entierly guaranteed that their style keys won't collide.
 */
var AtlasManager = /*#__PURE__*/function () {
  function AtlasManager(r, globalOptions) {
    _classCallCheck(this, AtlasManager);
    this.r = r;
    this.globalOptions = globalOptions;
    this.atlasSize = globalOptions.webglTexSize;
    this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
    this.renderTypes = new Map(); // renderType:string -> renderTypeOptions
    this.collections = new Map(); // collectionName:string -> AtlasCollection

    this.typeAndIdToKey = new Map(); // [renderType,id] => Array<style key>
  }
  return _createClass(AtlasManager, [{
    key: "getAtlasSize",
    value: function getAtlasSize() {
      return this.atlasSize;
    }
  }, {
    key: "addAtlasCollection",
    value: function addAtlasCollection(collectionName, atlasCollectionOptions) {
      var _this$globalOptions = this.globalOptions,
        webglTexSize = _this$globalOptions.webglTexSize,
        createTextureCanvas = _this$globalOptions.createTextureCanvas;
      var texRows = atlasCollectionOptions.texRows;
      var cachedCreateTextureCanvas = this._cacheScratchCanvas(createTextureCanvas);
      var atlasCollection = new AtlasCollection(this.r, webglTexSize, texRows, cachedCreateTextureCanvas);
      this.collections.set(collectionName, atlasCollection);
    }
  }, {
    key: "addRenderType",
    value: function addRenderType(type, renderTypeOptions) {
      var collection = renderTypeOptions.collection;
      if (!this.collections.has(collection)) throw new Error("invalid atlas collection name '".concat(collection, "'"));
      var atlasCollection = this.collections.get(collection);
      var opts = extend({
        type: type,
        atlasCollection: atlasCollection
      }, renderTypeOptions);
      this.renderTypes.set(type, opts);
    }
  }, {
    key: "getRenderTypeOpts",
    value: function getRenderTypeOpts(type) {
      return this.renderTypes.get(type);
    }
  }, {
    key: "getAtlasCollection",
    value: function getAtlasCollection(name) {
      return this.collections.get(name);
    }
  }, {
    key: "_cacheScratchCanvas",
    value: function _cacheScratchCanvas(createTextureCanvas) {
      // all scratch canvases for the same render type will have the same width and height (ie webglTexRows option)
      // but we'll keep track of the width and height just to be safe
      var prevW = -1;
      var prevH = -1;
      var scratchCanvas = null;
      return function (r, w, h, scratch) {
        if (scratch) {
          if (!scratchCanvas || w != prevW || h != prevH) {
            prevW = w;
            prevH = h;
            scratchCanvas = createTextureCanvas(r, w, h);
          }
          return scratchCanvas;
        } else {
          return createTextureCanvas(r, w, h);
        }
      };
    }
  }, {
    key: "_key",
    value: function _key(renderType, id) {
      return "".concat(renderType, "-").concat(id); // TODO not very efficient
    }

    /** Marks textues associated with the element for garbage collection. */
  }, {
    key: "invalidate",
    value: function invalidate(eles) {
      var _this3 = this;
      var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
        _ref2$forceRedraw = _ref2.forceRedraw,
        forceRedraw = _ref2$forceRedraw === undefined ? false : _ref2$forceRedraw,
        _ref2$filterEle = _ref2.filterEle,
        filterEle = _ref2$filterEle === undefined ? function () {
          return true;
        } : _ref2$filterEle,
        _ref2$filterType = _ref2.filterType,
        filterType = _ref2$filterType === undefined ? function () {
          return true;
        } : _ref2$filterType;
      var needGC = false;
      var runGCNow = false;
      var _iterator3 = _createForOfIteratorHelper(eles),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var ele = _step3.value;
          if (filterEle(ele)) {
            var _iterator4 = _createForOfIteratorHelper(this.renderTypes.values()),
              _step4;
            try {
              var _loop2 = function _loop2() {
                var opts = _step4.value;
                var renderType = opts.type;
                if (filterType(renderType)) {
                  var atlasCollection = _this3.collections.get(opts.collection);
                  var key = opts.getKey(ele);
                  var keyArray = Array.isArray(key) ? key : [key];

                  // when a node's background image finishes loading, the style key doesn't change but still needs to be redrawn
                  if (forceRedraw) {
                    keyArray.forEach(function (key) {
                      return atlasCollection.markKeyForGC(key);
                    });
                    runGCNow = true; // run GC to remove the old texture right now, that way we don't need to remember for the next gc 
                  } else {
                    var id = opts.getID ? opts.getID(ele) : ele.id();
                    var mapKey = _this3._key(renderType, id);
                    var oldKeyArray = _this3.typeAndIdToKey.get(mapKey);
                    if (oldKeyArray !== undefined && !arrayEqual(keyArray, oldKeyArray)) {
                      // conservative approach, if any of the keys don't match then throw them all away
                      needGC = true;
                      _this3.typeAndIdToKey["delete"](mapKey);
                      oldKeyArray.forEach(function (oldKey) {
                        return atlasCollection.markKeyForGC(oldKey);
                      });
                    }
                  }
                }
              };
              for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
                _loop2();
              }
            } catch (err) {
              _iterator4.e(err);
            } finally {
              _iterator4.f();
            }
          }
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
      if (runGCNow) {
        this.gc();
        needGC = false;
      }
      return needGC;
    }

    /** Garbage collect */
  }, {
    key: "gc",
    value: function gc() {
      var _iterator5 = _createForOfIteratorHelper(this.collections.values()),
        _step5;
      try {
        for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
          var collection = _step5.value;
          collection.gc();
        }
      } catch (err) {
        _iterator5.e(err);
      } finally {
        _iterator5.f();
      }
    }
  }, {
    key: "getOrCreateAtlas",
    value: function getOrCreateAtlas(ele, type, bb, styleKey) {
      // styleKey is not an array here
      var opts = this.renderTypes.get(type);
      var atlasCollection = this.collections.get(opts.collection);

      // draws the texture only if needed
      var drawn = false;
      var atlas = atlasCollection.draw(styleKey, bb, function (context) {
        if (opts.drawClipped) {
          context.save();
          context.beginPath();
          context.rect(0, 0, bb.w, bb.h);
          context.clip();
          opts.drawElement(context, ele, bb, true, true);
          context.restore();
        } else {
          opts.drawElement(context, ele, bb, true, true);
        }
        drawn = true;
      });
      if (drawn) {
        var id = opts.getID ? opts.getID(ele) : ele.id(); // for testing
        var mapKey = this._key(type, id);
        if (this.typeAndIdToKey.has(mapKey)) {
          this.typeAndIdToKey.get(mapKey).push(styleKey);
        } else {
          this.typeAndIdToKey.set(mapKey, [styleKey]);
        }
      }
      return atlas;
    }
  }, {
    key: "getAtlasInfo",
    value: function getAtlasInfo(ele, type) {
      var _this4 = this;
      var opts = this.renderTypes.get(type);
      var key = opts.getKey(ele);
      var keyArray = Array.isArray(key) ? key : [key];
      return keyArray.map(function (styleKey) {
        var bb = opts.getBoundingBox(ele, styleKey); // pass the key back to the getBoundingBox method
        var atlas = _this4.getOrCreateAtlas(ele, type, bb, styleKey);
        var _atlas$getOffsets3 = atlas.getOffsets(styleKey),
          _atlas$getOffsets4 = _slicedToArray(_atlas$getOffsets3, 2),
          tex1 = _atlas$getOffsets4[0],
          tex2 = _atlas$getOffsets4[1];
        return {
          atlas: atlas,
          tex: tex1,
          tex1: tex1,
          tex2: tex2,
          bb: bb
        };
      });
    }
  }, {
    key: "getDebugInfo",
    value: function getDebugInfo() {
      var debugInfo = [];
      var _iterator6 = _createForOfIteratorHelper(this.collections),
        _step6;
      try {
        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
          var _step6$value = _slicedToArray(_step6.value, 2),
            name = _step6$value[0],
            collection = _step6$value[1];
          var _collection$getCounts = collection.getCounts(),
            keyCount = _collection$getCounts.keyCount,
            atlasCount = _collection$getCounts.atlasCount;
          debugInfo.push({
            type: name,
            keyCount: keyCount,
            atlasCount: atlasCount
          });
        }
      } catch (err) {
        _iterator6.e(err);
      } finally {
        _iterator6.f();
      }
      return debugInfo;
    }
  }]);
}();
var AtlasBatchManager = /*#__PURE__*/function () {
  function AtlasBatchManager(globalOptions) {
    _classCallCheck(this, AtlasBatchManager);
    this.globalOptions = globalOptions;
    this.atlasSize = globalOptions.webglTexSize;
    this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
    this.batchAtlases = [];
  }
  return _createClass(AtlasBatchManager, [{
    key: "getMaxAtlasesPerBatch",
    value: function getMaxAtlasesPerBatch() {
      return this.maxAtlasesPerBatch;
    }
  }, {
    key: "getAtlasSize",
    value: function getAtlasSize() {
      return this.atlasSize;
    }
  }, {
    key: "getIndexArray",
    value: function getIndexArray() {
      return Array.from({
        length: this.maxAtlasesPerBatch
      }, function (v, i) {
        return i;
      });
    }
  }, {
    key: "startBatch",
    value: function startBatch() {
      this.batchAtlases = [];
    }
  }, {
    key: "getAtlasCount",
    value: function getAtlasCount() {
      return this.batchAtlases.length;
    }
  }, {
    key: "getAtlases",
    value: function getAtlases() {
      return this.batchAtlases;
    }
  }, {
    key: "canAddToCurrentBatch",
    value: function canAddToCurrentBatch(atlas) {
      if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
        return this.batchAtlases.includes(atlas);
      }
      return true; // not full
    }
  }, {
    key: "getAtlasIndexForBatch",
    value: function getAtlasIndexForBatch(atlas) {
      var atlasID = this.batchAtlases.indexOf(atlas);
      if (atlasID < 0) {
        if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
          throw new Error('cannot add more atlases to batch');
        }
        this.batchAtlases.push(atlas);
        atlasID = this.batchAtlases.length - 1;
      }
      return atlasID;
    }
  }]);
}();

// Fragment shader functions to calculate signed distance
// https://iquilezles.org/articles/distfunctions2d/
// ellipse: https://www.shadertoy.com/view/4lsXDN 

/**
 * param p - point
 * float r - circle radius, eg 0.5 for unit circle
 */
var circleSD = "\n  float circleSD(vec2 p, float r) {\n    return distance(vec2(0), p) - r; // signed distance\n  }\n";

/**
 * param p - point
 * param b - b.x = half width, b.y = half height
 */
var rectangleSD = "\n  float rectangleSD(vec2 p, vec2 b) {\n    vec2 d = abs(p)-b;\n    return distance(vec2(0),max(d,0.0)) + min(max(d.x,d.y),0.0);\n  }\n";

/**
 * param p - point
 * param b - b.x = half width, b.y = half height
 * param cr - vector of corner radiuses
 */
var roundRectangleSD = "\n  float roundRectangleSD(vec2 p, vec2 b, vec4 cr) {\n    cr.xy = (p.x > 0.0) ? cr.xy : cr.zw;\n    cr.x  = (p.y > 0.0) ? cr.x  : cr.y;\n    vec2 q = abs(p) - b + cr.x;\n    return min(max(q.x, q.y), 0.0) + distance(vec2(0), max(q, 0.0)) - cr.x;\n  }\n";

/**
 * param p - point
 * param ab - a.x = horizontal radius, a.y = vertical radius
 */
var ellipseSD = "\n  float ellipseSD(vec2 p, vec2 ab) {\n    p = abs( p ); // symmetry\n\n    // find root with Newton solver\n    vec2 q = ab*(p-ab);\n    float w = (q.x<q.y)? 1.570796327 : 0.0;\n    for( int i=0; i<5; i++ ) {\n      vec2 cs = vec2(cos(w),sin(w));\n      vec2 u = ab*vec2( cs.x,cs.y);\n      vec2 v = ab*vec2(-cs.y,cs.x);\n      w = w + dot(p-u,v)/(dot(p-u,u)+dot(v,v));\n    }\n    \n    // compute final point and distance\n    float d = length(p-ab*vec2(cos(w),sin(w)));\n    \n    // return signed distance\n    return (dot(p/ab,p/ab)>1.0) ? d : -d;\n  }\n";

/**
 * Two render modes. Each mode has its own shader program. They are almost identical, the main difference is the output.
 * SCREEN:  output pixel colors to the screen
 * PICKING: output z-order index to an offscreen framebuffer, used to detect what's under the mouse cursor
 */
var RENDER_TARGET = {
  SCREEN: {
    name: 'screen',
    screen: true
  },
  PICKING: {
    name: 'picking',
    picking: true
  }
};

/**
 * Special handing for label textures in PICKING mode. See issue #3337.
 */
var TEX_PICKING_MODE = {
  // render the texture just like in RENDER_TARGET.SCREEN mode
  IGNORE: 1,
  // don't render the texture at all
  USE_BB: 2 // render the bounding box as an opaque rectangle
};

// Vertex types.
// Used directly in the shaders so must be numeric.
// There is only one shader program used for an entire frame that renders all types of elements.
// There are if-else blocks in the shaders that do different things depending on the vertex type.
// This allows all elements to be rendererd in large batches without switching shader programs.
var TEXTURE = 0;
var EDGE_STRAIGHT = 1;
var EDGE_CURVE_SEGMENT = 2;
var EDGE_ARROW = 3;
var RECTANGLE = 4;
var ROUND_RECTANGLE = 5;
var BOTTOM_ROUND_RECTANGLE = 6;
var ELLIPSE = 7;
var ElementDrawingWebGL = /*#__PURE__*/function () {
  /**
   * @param {WebGLRenderingContext} gl
   */
  function ElementDrawingWebGL(r, gl, opts) {
    _classCallCheck(this, ElementDrawingWebGL);
    this.r = r; // reference to the canvas renderer
    this.gl = gl;
    this.maxInstances = opts.webglBatchSize;
    this.atlasSize = opts.webglTexSize;
    this.bgColor = opts.bgColor;
    this.debug = opts.webglDebug;
    this.batchDebugInfo = [];
    opts.enableWrapping = true;
    opts.createTextureCanvas = createTextureCanvas; // Unit tests mock this

    this.atlasManager = new AtlasManager(r, opts);
    this.batchManager = new AtlasBatchManager(opts);
    this.simpleShapeOptions = new Map();
    this.program = this._createShaderProgram(RENDER_TARGET.SCREEN);
    this.pickingProgram = this._createShaderProgram(RENDER_TARGET.PICKING);
    this.vao = this._createVAO();
  }

  /**
   * @param { string } collectionName
   * @param {{ texRows: number }} opts
   */
  return _createClass(ElementDrawingWebGL, [{
    key: "addAtlasCollection",
    value: function addAtlasCollection(collectionName, opts) {
      this.atlasManager.addAtlasCollection(collectionName, opts);
    }

    /**
     * @typedef { Object } TextureRenderTypeOpts
     * @property { string } collection - name of atlas collection to render textures to
     * @property { function } getKey - returns the "style key" for an element, may be a single value or an array for multi-line lables
     * @property { function } drawElement - uses a canvas renderer to draw the element to the texture atlas
     * @property { boolean  } drawClipped - if true the context will be clipped to the bounding box before drawElement() is called, may affect performance
     * @property { function } getBoundingBox - returns the bounding box for an element
     * @property { function } getRotation
     * @property { function } getRotationPoint
     * @property { function } getRotationOffset
     * @property { function } isVisible - an extra check for visibility in addition to ele.visible()
     * @property { function } getTexPickingMode - returns a value from the TEX_PICKING_MODE enum
     */
    /**
     * @param { string } typeName
     * @param { TextureRenderTypeOpts } opts
     */
  }, {
    key: "addTextureAtlasRenderType",
    value: function addTextureAtlasRenderType(typeName, opts) {
      this.atlasManager.addRenderType(typeName, opts);
    }

    /**
     * @typedef { Object } SimpleShapeRenderTypeOpts
     * @property { function } getBoundingBox - returns the bounding box for an element
     * @property { function } isVisible - this is an extra check for visibility in addition to ele.visible()
     * @property { function } isSimple - check if element is a simple shape, or if it needs to fall back to texture rendering
     * @property { ShapeVisualProperties } shapeProps
     */
    /**
     * @typedef { Object } ShapeVisualProperties
     * @property { string } shape
     * @property { string } color
     * @property { string } opacity
     * @property { string } padding
     * @property { string } radius
     * @property { boolean } border
    */
    /**
     * @param { string } typeName
     * @param { SimpleShapeRenderTypeOpts } opts
     */
  }, {
    key: "addSimpleShapeRenderType",
    value: function addSimpleShapeRenderType(typeName, opts) {
      this.simpleShapeOptions.set(typeName, opts);
    }

    /**
     * Inform the atlasManager when element style keys may have changed.
     * The atlasManager can then mark unused textures for "garbage collection".
     */
  }, {
    key: "invalidate",
    value: function invalidate(eles) {
      var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
        type = _ref.type;
      var atlasManager = this.atlasManager;
      if (type) {
        return atlasManager.invalidate(eles, {
          filterType: function filterType(t) {
            return t === type;
          },
          forceRedraw: true
        });
      } else {
        return atlasManager.invalidate(eles);
      }
    }

    /**
     * Run texture garbage collection.
     */
  }, {
    key: "gc",
    value: function gc() {
      this.atlasManager.gc();
    }
  }, {
    key: "_createShaderProgram",
    value: function _createShaderProgram(renderTarget) {
      var gl = this.gl;
      var vertexShaderSource = "#version 300 es\n      precision highp float;\n\n      uniform mat3 uPanZoomMatrix;\n      uniform int  uAtlasSize;\n      \n      // instanced\n      in vec2 aPosition; // a vertex from the unit square\n      \n      in mat3 aTransform; // used to transform verticies, eg into a bounding box\n      in int aVertType; // the type of thing we are rendering\n\n      // the z-index that is output when using picking mode\n      in vec4 aIndex;\n      \n      // For textures\n      in int aAtlasId; // which shader unit/atlas to use\n      in vec4 aTex; // x/y/w/h of texture in atlas\n\n      // for edges\n      in vec4 aPointAPointB;\n      in vec4 aPointCPointD;\n      in vec2 aLineWidth; // also used for node border width\n\n      // simple shapes\n      in vec4 aCornerRadius; // for round-rectangle [top-right, bottom-right, top-left, bottom-left]\n      in vec4 aColor; // also used for edges\n      in vec4 aBorderColor; // aLineWidth is used for border width\n\n      // output values passed to the fragment shader\n      out vec2 vTexCoord;\n      out vec4 vColor;\n      out vec2 vPosition;\n      // flat values are not interpolated\n      flat out int vAtlasId; \n      flat out int vVertType;\n      flat out vec2 vTopRight;\n      flat out vec2 vBotLeft;\n      flat out vec4 vCornerRadius;\n      flat out vec4 vBorderColor;\n      flat out vec2 vBorderWidth;\n      flat out vec4 vIndex;\n      \n      void main(void) {\n        int vid = gl_VertexID;\n        vec2 position = aPosition; // TODO make this a vec3, simplifies some code below\n\n        if(aVertType == ".concat(TEXTURE, ") {\n          float texX = aTex.x; // texture coordinates\n          float texY = aTex.y;\n          float texW = aTex.z;\n          float texH = aTex.w;\n\n          if(vid == 1 || vid == 2 || vid == 4) {\n            texX += texW;\n          }\n          if(vid == 2 || vid == 4 || vid == 5) {\n            texY += texH;\n          }\n\n          float d = float(uAtlasSize);\n          vTexCoord = vec2(texX / d, texY / d); // tex coords must be between 0 and 1\n\n          gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\n        }\n        else if(aVertType == ").concat(RECTANGLE, " || aVertType == ").concat(ELLIPSE, " \n             || aVertType == ").concat(ROUND_RECTANGLE, " || aVertType == ").concat(BOTTOM_ROUND_RECTANGLE, ") { // simple shapes\n\n          // the bounding box is needed by the fragment shader\n          vBotLeft  = (aTransform * vec3(0, 0, 1)).xy; // flat\n          vTopRight = (aTransform * vec3(1, 1, 1)).xy; // flat\n          vPosition = (aTransform * vec3(position, 1)).xy; // will be interpolated\n\n          // calculations are done in the fragment shader, just pass these along\n          vColor = aColor;\n          vCornerRadius = aCornerRadius;\n          vBorderColor = aBorderColor;\n          vBorderWidth = aLineWidth;\n\n          gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\n        }\n        else if(aVertType == ").concat(EDGE_STRAIGHT, ") {\n          vec2 source = aPointAPointB.xy;\n          vec2 target = aPointAPointB.zw;\n\n          // adjust the geometry so that the line is centered on the edge\n          position.y = position.y - 0.5;\n\n          // stretch the unit square into a long skinny rectangle\n          vec2 xBasis = target - source;\n          vec2 yBasis = normalize(vec2(-xBasis.y, xBasis.x));\n          vec2 point = source + xBasis * position.x + yBasis * aLineWidth[0] * position.y;\n\n          gl_Position = vec4(uPanZoomMatrix * vec3(point, 1.0), 1.0);\n          vColor = aColor;\n        } \n        else if(aVertType == ").concat(EDGE_CURVE_SEGMENT, ") {\n          vec2 pointA = aPointAPointB.xy;\n          vec2 pointB = aPointAPointB.zw;\n          vec2 pointC = aPointCPointD.xy;\n          vec2 pointD = aPointCPointD.zw;\n\n          // adjust the geometry so that the line is centered on the edge\n          position.y = position.y - 0.5;\n\n          vec2 p0, p1, p2, pos;\n          if(position.x == 0.0) { // The left side of the unit square\n            p0 = pointA;\n            p1 = pointB;\n            p2 = pointC;\n            pos = position;\n          } else { // The right side of the unit square, use same approach but flip the geometry upside down\n            p0 = pointD;\n            p1 = pointC;\n            p2 = pointB;\n            pos = vec2(0.0, -position.y);\n          }\n\n          vec2 p01 = p1 - p0;\n          vec2 p12 = p2 - p1;\n          vec2 p21 = p1 - p2;\n\n          // Find the normal vector.\n          vec2 tangent = normalize(normalize(p12) + normalize(p01));\n          vec2 normal = vec2(-tangent.y, tangent.x);\n\n          // Find the vector perpendicular to p0 -> p1.\n          vec2 p01Norm = normalize(vec2(-p01.y, p01.x));\n\n          // Determine the bend direction.\n          float sigma = sign(dot(p01 + p21, normal));\n          float width = aLineWidth[0];\n\n          if(sign(pos.y) == -sigma) {\n            // This is an intersecting vertex. Adjust the position so that there's no overlap.\n            vec2 point = 0.5 * width * normal * -sigma / dot(normal, p01Norm);\n            gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0);\n          } else {\n            // This is a non-intersecting vertex. Treat it like a mitre join.\n            vec2 point = 0.5 * width * normal * sigma * dot(normal, p01Norm);\n            gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0);\n          }\n\n          vColor = aColor;\n        } \n        else if(aVertType == ").concat(EDGE_ARROW, " && vid < 3) {\n          // massage the first triangle into an edge arrow\n          if(vid == 0)\n            position = vec2(-0.15, -0.3);\n          if(vid == 1)\n            position = vec2(  0.0,  0.0);\n          if(vid == 2)\n            position = vec2( 0.15, -0.3);\n\n          gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\n          vColor = aColor;\n        }\n        else {\n          gl_Position = vec4(2.0, 0.0, 0.0, 1.0); // discard vertex by putting it outside webgl clip space\n        }\n\n        vAtlasId = aAtlasId;\n        vVertType = aVertType;\n        vIndex = aIndex;\n      }\n    ");
      var idxs = this.batchManager.getIndexArray();
      var fragmentShaderSource = "#version 300 es\n      precision highp float;\n\n      // declare texture unit for each texture atlas in the batch\n      ".concat(idxs.map(function (i) {
        return "uniform sampler2D uTexture".concat(i, ";");
      }).join('\n\t'), "\n\n      uniform vec4 uBGColor;\n      uniform float uZoom;\n\n      in vec2 vTexCoord;\n      in vec4 vColor;\n      in vec2 vPosition; // model coordinates\n\n      flat in int vAtlasId;\n      flat in vec4 vIndex;\n      flat in int vVertType;\n      flat in vec2 vTopRight;\n      flat in vec2 vBotLeft;\n      flat in vec4 vCornerRadius;\n      flat in vec4 vBorderColor;\n      flat in vec2 vBorderWidth;\n\n      out vec4 outColor;\n\n      ").concat(circleSD, "\n      ").concat(rectangleSD, "\n      ").concat(roundRectangleSD, "\n      ").concat(ellipseSD, "\n\n      vec4 blend(vec4 top, vec4 bot) { // blend colors with premultiplied alpha\n        return vec4( \n          top.rgb + (bot.rgb * (1.0 - top.a)),\n          top.a   + (bot.a   * (1.0 - top.a)) \n        );\n      }\n\n      vec4 distInterp(vec4 cA, vec4 cB, float d) { // interpolate color using Signed Distance\n        // scale to the zoom level so that borders don't look blurry when zoomed in\n        // note 1.5 is an aribitrary value chosen because it looks good\n        return mix(cA, cB, 1.0 - smoothstep(0.0, 1.5 / uZoom, abs(d))); \n      }\n\n      void main(void) {\n        if(vVertType == ").concat(TEXTURE, ") {\n          // look up the texel from the texture unit\n          ").concat(idxs.map(function (i) {
        return "if(vAtlasId == ".concat(i, ") outColor = texture(uTexture").concat(i, ", vTexCoord);");
      }).join('\n\telse '), "\n        } \n        else if(vVertType == ").concat(EDGE_ARROW, ") {\n          // mimics how canvas renderer uses context.globalCompositeOperation = 'destination-out';\n          outColor = blend(vColor, uBGColor);\n          outColor.a = 1.0; // make opaque, masks out line under arrow\n        }\n        else if(vVertType == ").concat(RECTANGLE, " && vBorderWidth == vec2(0.0)) { // simple rectangle with no border\n          outColor = vColor; // unit square is already transformed to the rectangle, nothing else needs to be done\n        }\n        else if(vVertType == ").concat(RECTANGLE, " || vVertType == ").concat(ELLIPSE, " \n          || vVertType == ").concat(ROUND_RECTANGLE, " || vVertType == ").concat(BOTTOM_ROUND_RECTANGLE, ") { // use SDF\n\n          float outerBorder = vBorderWidth[0];\n          float innerBorder = vBorderWidth[1];\n          float borderPadding = outerBorder * 2.0;\n          float w = vTopRight.x - vBotLeft.x - borderPadding;\n          float h = vTopRight.y - vBotLeft.y - borderPadding;\n          vec2 b = vec2(w/2.0, h/2.0); // half width, half height\n          vec2 p = vPosition - vec2(vTopRight.x - b[0] - outerBorder, vTopRight.y - b[1] - outerBorder); // translate to center\n\n          float d; // signed distance\n          if(vVertType == ").concat(RECTANGLE, ") {\n            d = rectangleSD(p, b);\n          } else if(vVertType == ").concat(ELLIPSE, " && w == h) {\n            d = circleSD(p, b.x); // faster than ellipse\n          } else if(vVertType == ").concat(ELLIPSE, ") {\n            d = ellipseSD(p, b);\n          } else {\n            d = roundRectangleSD(p, b, vCornerRadius.wzyx);\n          }\n\n          // use the distance to interpolate a color to smooth the edges of the shape, doesn't need multisampling\n          // we must smooth colors inwards, because we can't change pixels outside the shape's bounding box\n          if(d > 0.0) {\n            if(d > outerBorder) {\n              discard;\n            } else {\n              outColor = distInterp(vBorderColor, vec4(0), d - outerBorder);\n            }\n          } else {\n            if(d > innerBorder) {\n              vec4 outerColor = outerBorder == 0.0 ? vec4(0) : vBorderColor;\n              vec4 innerBorderColor = blend(vBorderColor, vColor);\n              outColor = distInterp(innerBorderColor, outerColor, d);\n            } \n            else {\n              vec4 outerColor;\n              if(innerBorder == 0.0 && outerBorder == 0.0) {\n                outerColor = vec4(0);\n              } else if(innerBorder == 0.0) {\n                outerColor = vBorderColor;\n              } else {\n                outerColor = blend(vBorderColor, vColor);\n              }\n              outColor = distInterp(vColor, outerColor, d - innerBorder);\n            }\n          }\n        }\n        else {\n          outColor = vColor;\n        }\n\n        ").concat(renderTarget.picking ? "if(outColor.a == 0.0) discard;\n             else outColor = vIndex;" : '', "\n      }\n    ");
      var program = createProgram(gl, vertexShaderSource, fragmentShaderSource);

      // instance geometry
      program.aPosition = gl.getAttribLocation(program, 'aPosition');

      // attributes
      program.aIndex = gl.getAttribLocation(program, 'aIndex');
      program.aVertType = gl.getAttribLocation(program, 'aVertType');
      program.aTransform = gl.getAttribLocation(program, 'aTransform');
      program.aAtlasId = gl.getAttribLocation(program, 'aAtlasId');
      program.aTex = gl.getAttribLocation(program, 'aTex');
      program.aPointAPointB = gl.getAttribLocation(program, 'aPointAPointB');
      program.aPointCPointD = gl.getAttribLocation(program, 'aPointCPointD');
      program.aLineWidth = gl.getAttribLocation(program, 'aLineWidth');
      program.aColor = gl.getAttribLocation(program, 'aColor');
      program.aCornerRadius = gl.getAttribLocation(program, 'aCornerRadius');
      program.aBorderColor = gl.getAttribLocation(program, 'aBorderColor');

      // uniforms
      program.uPanZoomMatrix = gl.getUniformLocation(program, 'uPanZoomMatrix');
      program.uAtlasSize = gl.getUniformLocation(program, 'uAtlasSize');
      program.uBGColor = gl.getUniformLocation(program, 'uBGColor');
      program.uZoom = gl.getUniformLocation(program, 'uZoom');
      program.uTextures = [];
      for (var i = 0; i < this.batchManager.getMaxAtlasesPerBatch(); i++) {
        program.uTextures.push(gl.getUniformLocation(program, "uTexture".concat(i)));
      }
      return program;
    }
  }, {
    key: "_createVAO",
    value: function _createVAO() {
      var unitSquare = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1];
      this.vertexCount = unitSquare.length / 2;
      var n = this.maxInstances;
      var gl = this.gl,
        program = this.program;
      var vao = gl.createVertexArray();
      gl.bindVertexArray(vao);
      createBufferStaticDraw(gl, 'vec2', program.aPosition, unitSquare);

      // Create buffers for all the attributes
      this.transformBuffer = create3x3MatrixBufferDynamicDraw(gl, n, program.aTransform);
      this.indexBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aIndex);
      this.vertTypeBuffer = createBufferDynamicDraw(gl, n, 'int', program.aVertType);
      this.atlasIdBuffer = createBufferDynamicDraw(gl, n, 'int', program.aAtlasId);
      this.texBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aTex);
      this.pointAPointBBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointAPointB);
      this.pointCPointDBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointCPointD);
      this.lineWidthBuffer = createBufferDynamicDraw(gl, n, 'vec2', program.aLineWidth);
      this.colorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aColor);
      this.cornerRadiusBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aCornerRadius);
      this.borderColorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aBorderColor);
      gl.bindVertexArray(null);
      return vao;
    }
  }, {
    key: "buffers",
    get: function get() {
      var _this = this;
      if (!this._buffers) {
        this._buffers = Object.keys(this).filter(function (k) {
          return endsWith(k, 'Buffer');
        }).map(function (k) {
          return _this[k];
        });
      }
      return this._buffers;
    }
  }, {
    key: "startFrame",
    value: function startFrame(panZoomMatrix) {
      var renderTarget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : RENDER_TARGET.SCREEN;
      this.panZoomMatrix = panZoomMatrix;
      this.renderTarget = renderTarget;
      this.batchDebugInfo = [];
      this.wrappedCount = 0;
      this.simpleCount = 0;
      this.startBatch();
    }
  }, {
    key: "startBatch",
    value: function startBatch() {
      this.instanceCount = 0;
      this.batchManager.startBatch();
    }
  }, {
    key: "endFrame",
    value: function endFrame() {
      this.endBatch();
    }
  }, {
    key: "_isVisible",
    value: function _isVisible(ele, opts) {
      if (ele.visible()) {
        if (opts && opts.isVisible) {
          return opts.isVisible(ele);
        }
        return true;
      }
      return false;
    }

    /**
     * Draws a texture using the texture atlas.
     */
  }, {
    key: "drawTexture",
    value: function drawTexture(ele, eleIndex, type) {
      var atlasManager = this.atlasManager,
        batchManager = this.batchManager;
      var opts = atlasManager.getRenderTypeOpts(type);
      if (!this._isVisible(ele, opts)) {
        return;
      }
      if (this.renderTarget.picking && opts.getTexPickingMode) {
        var mode = opts.getTexPickingMode(ele);
        if (mode === TEX_PICKING_MODE.IGNORE) {
          return;
        } else if (mode == TEX_PICKING_MODE.USE_BB) {
          this.drawPickingRectangle(ele, eleIndex, type);
          return;
        }
      }

      // Get the atlas and the texture coordinates, will draw the texture if it hasn't been drawn yet
      // May be more than one texture if for example the label has multiple lines
      var atlasInfoArray = atlasManager.getAtlasInfo(ele, type);
      var _iterator = _createForOfIteratorHelper(atlasInfoArray),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var atlasInfo = _step.value;
          var atlas = atlasInfo.atlas,
            tex1 = atlasInfo.tex1,
            tex2 = atlasInfo.tex2; // tex2 is used if the label wraps and there are two textures

          if (!batchManager.canAddToCurrentBatch(atlas)) {
            this.endBatch();
          }
          var atlasIndex = batchManager.getAtlasIndexForBatch(atlas);
          for (var _i = 0, _arr = [[tex1, true], [tex2, false]]; _i < _arr.length; _i++) {
            var _arr$_i = _slicedToArray(_arr[_i], 2),
              tex = _arr$_i[0],
              first = _arr$_i[1];
            if (tex.w != 0) {
              var instance = this.instanceCount;
              this.vertTypeBuffer.getView(instance)[0] = TEXTURE;
              var indexView = this.indexBuffer.getView(instance);
              indexToVec4(eleIndex, indexView);

              // Set values in the buffers using Typed Array Views for performance.
              var atlasIdView = this.atlasIdBuffer.getView(instance);
              atlasIdView[0] = atlasIndex;

              // we have two sets of texture coordinates and transforms because textures can wrap in the atlas
              var texView = this.texBuffer.getView(instance);
              texView[0] = tex.x;
              texView[1] = tex.y;
              texView[2] = tex.w;
              texView[3] = tex.h;
              var matrixView = this.transformBuffer.getMatrixView(instance);
              this.setTransformMatrix(ele, matrixView, opts, atlasInfo, first);
              this.instanceCount++;
              if (!first) this.wrappedCount++;
              if (this.instanceCount >= this.maxInstances) {
                this.endBatch();
              }
            }
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }

    /**
     * matrix is expected to be a 9 element array
     * this function follows same pattern as CRp.drawCachedElementPortion(...)
     */
  }, {
    key: "setTransformMatrix",
    value: function setTransformMatrix(ele, matrix, opts, atlasInfo) {
      var first = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
      var padding = 0;
      if (opts.shapeProps && opts.shapeProps.padding) {
        padding = ele.pstyle(opts.shapeProps.padding).pfValue;
      }
      if (atlasInfo) {
        // we've already computed the bb and tex bounds for a texture
        var bb = atlasInfo.bb,
          tex1 = atlasInfo.tex1,
          tex2 = atlasInfo.tex2;
        // wrapped textures need separate matrix for each part
        var ratio = tex1.w / (tex1.w + tex2.w);
        if (!first) {
          // first = true means its the first part of the wrapped texture
          ratio = 1 - ratio;
        }
        var adjBB = this._getAdjustedBB(bb, padding, first, ratio);
        this._applyTransformMatrix(matrix, adjBB, opts, ele);
      } else {
        // we don't have a texture, or we want to avoid creating a texture for simple shapes
        var _bb = opts.getBoundingBox(ele);
        var _adjBB = this._getAdjustedBB(_bb, padding, true, 1);
        this._applyTransformMatrix(matrix, _adjBB, opts, ele);
      }
    }
  }, {
    key: "_applyTransformMatrix",
    value: function _applyTransformMatrix(matrix, adjBB, opts, ele) {
      var x, y;
      identity(matrix);
      var theta = opts.getRotation ? opts.getRotation(ele) : 0;
      if (theta !== 0) {
        var _opts$getRotationPoin = opts.getRotationPoint(ele),
          sx = _opts$getRotationPoin.x,
          sy = _opts$getRotationPoin.y;
        translate(matrix, matrix, [sx, sy]);
        rotate(matrix, matrix, theta);
        var offset = opts.getRotationOffset(ele);
        x = offset.x + (adjBB.xOffset || 0);
        y = offset.y + (adjBB.yOffset || 0);
      } else {
        x = adjBB.x1;
        y = adjBB.y1;
      }
      translate(matrix, matrix, [x, y]);
      scale(matrix, matrix, [adjBB.w, adjBB.h]);
    }

    /**
     * Adjusts a node or label BB to accomodate padding and split for wrapped textures.
     * @param bb - the original bounding box
     * @param padding - the padding to add to the bounding box
     * @param first - whether this is the first part of a wrapped texture
     * @param ratio - the ratio of the texture width of part of the text to the entire texture
     */
  }, {
    key: "_getAdjustedBB",
    value: function _getAdjustedBB(bb, padding, first, ratio) {
      var x1 = bb.x1,
        y1 = bb.y1,
        w = bb.w,
        h = bb.h,
        yOffset = bb.yOffset;
      if (padding) {
        x1 -= padding;
        y1 -= padding;
        w += 2 * padding;
        h += 2 * padding;
      }
      var xOffset = 0;
      var adjW = w * ratio;
      if (first && ratio < 1) {
        w = adjW;
      } else if (!first && ratio < 1) {
        xOffset = w - adjW;
        x1 += xOffset;
        w = adjW;
      }
      return {
        x1: x1,
        y1: y1,
        w: w,
        h: h,
        xOffset: xOffset,
        yOffset: yOffset
      };
    }

    /**
     * Draw a solid opaque rectangle matching the element's Bounding Box.
     * Used by the PICKING mode to make the entire BB of a label clickable.
     */
  }, {
    key: "drawPickingRectangle",
    value: function drawPickingRectangle(ele, eleIndex, type) {
      var opts = this.atlasManager.getRenderTypeOpts(type);
      var instance = this.instanceCount;
      this.vertTypeBuffer.getView(instance)[0] = RECTANGLE;
      var indexView = this.indexBuffer.getView(instance);
      indexToVec4(eleIndex, indexView);
      var colorView = this.colorBuffer.getView(instance);
      toWebGLColor([0, 0, 0], 1, colorView); // opaque, so entire label BB is clickable

      var matrixView = this.transformBuffer.getMatrixView(instance);
      this.setTransformMatrix(ele, matrixView, opts);
      this.simpleCount++;
      this.instanceCount++;
      if (this.instanceCount >= this.maxInstances) {
        this.endBatch();
      }
    }

    /**
     * Draw a node using either a texture or a "simple shape".
     */
  }, {
    key: "drawNode",
    value: function drawNode(node, eleIndex, type) {
      var opts = this.simpleShapeOptions.get(type);
      if (!this._isVisible(node, opts)) {
        return;
      }
      var props = opts.shapeProps;

      // Check if we have to use a texture
      var vertType = this._getVertTypeForShape(node, props.shape);
      if (vertType === undefined || opts.isSimple && !opts.isSimple(node)) {
        this.drawTexture(node, eleIndex, type);
        return;
      }

      // Render a "simple shape" using SDF (signed distance fields)
      var instance = this.instanceCount;
      this.vertTypeBuffer.getView(instance)[0] = vertType;
      if (vertType === ROUND_RECTANGLE || vertType === BOTTOM_ROUND_RECTANGLE) {
        // get corner radius
        var bb = opts.getBoundingBox(node);
        var radius = this._getCornerRadius(node, props.radius, bb);
        var radiusView = this.cornerRadiusBuffer.getView(instance);
        radiusView[0] = radius; // top-right
        radiusView[1] = radius; // bottom-right
        radiusView[2] = radius; // top-left
        radiusView[3] = radius; // bottom-left
        if (vertType === BOTTOM_ROUND_RECTANGLE) {
          radiusView[0] = 0;
          radiusView[2] = 0;
        }
      }
      var indexView = this.indexBuffer.getView(instance);
      indexToVec4(eleIndex, indexView);
      var color = node.pstyle(props.color).value;
      var opacity = node.pstyle(props.opacity).value;
      var colorView = this.colorBuffer.getView(instance);
      toWebGLColor(color, opacity, colorView);
      var lineWidthView = this.lineWidthBuffer.getView(instance); // reuse edge line width attribute for node border
      lineWidthView[0] = 0;
      lineWidthView[1] = 0;
      if (props.border) {
        var borderWidth = node.pstyle('border-width').value;
        if (borderWidth > 0) {
          var borderColor = node.pstyle('border-color').value;
          var borderOpacity = node.pstyle('border-opacity').value;
          var borderColorView = this.borderColorBuffer.getView(instance);
          toWebGLColor(borderColor, borderOpacity, borderColorView);

          // SDF distance is negative inside the shape and positive outside
          var borderPos = node.pstyle('border-position').value;
          if (borderPos === 'inside') {
            lineWidthView[0] = 0;
            lineWidthView[1] = -borderWidth;
          } else if (borderPos === 'outside') {
            lineWidthView[0] = borderWidth;
            lineWidthView[1] = 0;
          } else {
            // 'center'
            var halfWidth = borderWidth / 2;
            lineWidthView[0] = halfWidth;
            lineWidthView[1] = -halfWidth;
          }
        }
      }
      var matrixView = this.transformBuffer.getMatrixView(instance);
      this.setTransformMatrix(node, matrixView, opts);
      this.simpleCount++;
      this.instanceCount++;
      if (this.instanceCount >= this.maxInstances) {
        this.endBatch();
      }
    }
  }, {
    key: "_getVertTypeForShape",
    value: function _getVertTypeForShape(node, shapeProp) {
      var shape = node.pstyle(shapeProp).value;
      switch (shape) {
        case 'rectangle':
          return RECTANGLE;
        case 'ellipse':
          return ELLIPSE;
        case 'roundrectangle':
        case 'round-rectangle':
          return ROUND_RECTANGLE;
        case 'bottom-round-rectangle':
          return BOTTOM_ROUND_RECTANGLE;
        default:
          return undefined;
      }
    }
  }, {
    key: "_getCornerRadius",
    value: function _getCornerRadius(node, radiusProp, _ref2) {
      var w = _ref2.w,
        h = _ref2.h;
      // see CRp.drawRoundRectanglePath
      if (node.pstyle(radiusProp).value === 'auto') {
        return getRoundRectangleRadius(w, h);
      } else {
        var radius = node.pstyle(radiusProp).pfValue;
        var halfWidth = w / 2;
        var halfHeight = h / 2;
        return Math.min(radius, halfHeight, halfWidth);
      }
    }

    /**
     * Only supports drawing triangles at the moment.
     */
  }, {
    key: "drawEdgeArrow",
    value: function drawEdgeArrow(edge, eleIndex, prefix) {
      if (!edge.visible()) {
        return;
      }
      // Edge points and arrow angles etc are calculated by the base renderer and cached in the rscratch object.
      var rs = edge._private.rscratch;
      var x, y, angle;
      if (prefix === 'source') {
        x = rs.arrowStartX;
        y = rs.arrowStartY;
        angle = rs.srcArrowAngle;
      } else {
        x = rs.arrowEndX;
        y = rs.arrowEndY;
        angle = rs.tgtArrowAngle;
      }

      // taken from CRp.drawArrowhead
      if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
        return;
      }

      // check shape after the x/y check because pstyle() is a bit slow
      var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
      if (arrowShape === 'none') {
        return;
      }
      var color = edge.pstyle(prefix + '-arrow-color').value;
      var baseOpacity = edge.pstyle('opacity').value;
      var lineOpacity = edge.pstyle('line-opacity').value;
      var opacity = baseOpacity * lineOpacity;
      var lineWidth = edge.pstyle('width').pfValue;
      var scale$1 = edge.pstyle('arrow-scale').value;
      var size = this.r.getArrowWidth(lineWidth, scale$1);
      var instance = this.instanceCount;
      var transform = this.transformBuffer.getMatrixView(instance);
      identity(transform);
      translate(transform, transform, [x, y]);
      scale(transform, transform, [size, size]);
      rotate(transform, transform, angle);
      this.vertTypeBuffer.getView(instance)[0] = EDGE_ARROW;
      var indexView = this.indexBuffer.getView(instance);
      indexToVec4(eleIndex, indexView);
      var colorView = this.colorBuffer.getView(instance);
      toWebGLColor(color, opacity, colorView);
      this.instanceCount++;
      if (this.instanceCount >= this.maxInstances) {
        this.endBatch();
      }
    }

    /**
     * Draw straight-line or bezier curve edges.
     */
  }, {
    key: "drawEdgeLine",
    value: function drawEdgeLine(edge, eleIndex) {
      if (!edge.visible()) {
        return;
      }
      var points = this._getEdgePoints(edge);
      if (!points) {
        return;
      }

      // line style
      var baseOpacity = edge.pstyle('opacity').value;
      var lineOpacity = edge.pstyle('line-opacity').value;
      var width = edge.pstyle('width').pfValue;
      var color = edge.pstyle('line-color').value;
      var opacity = baseOpacity * lineOpacity;
      if (points.length / 2 + this.instanceCount > this.maxInstances) {
        this.endBatch();
      }
      if (points.length == 4) {
        // straight line
        var instance = this.instanceCount;
        this.vertTypeBuffer.getView(instance)[0] = EDGE_STRAIGHT;
        var indexView = this.indexBuffer.getView(instance);
        indexToVec4(eleIndex, indexView);
        var colorView = this.colorBuffer.getView(instance);
        toWebGLColor(color, opacity, colorView);
        var lineWidthBuffer = this.lineWidthBuffer.getView(instance);
        lineWidthBuffer[0] = width;
        var sourceTargetView = this.pointAPointBBuffer.getView(instance);
        sourceTargetView[0] = points[0]; // source x
        sourceTargetView[1] = points[1]; // source y
        sourceTargetView[2] = points[2]; // target x
        sourceTargetView[3] = points[3]; // target y

        this.instanceCount++;
        if (this.instanceCount >= this.maxInstances) {
          this.endBatch();
        }
      } else {
        // curved line
        for (var i = 0; i < points.length - 2; i += 2) {
          var _instance = this.instanceCount;
          this.vertTypeBuffer.getView(_instance)[0] = EDGE_CURVE_SEGMENT;
          var _indexView = this.indexBuffer.getView(_instance);
          indexToVec4(eleIndex, _indexView);
          var _colorView = this.colorBuffer.getView(_instance);
          toWebGLColor(color, opacity, _colorView);
          var _lineWidthBuffer = this.lineWidthBuffer.getView(_instance);
          _lineWidthBuffer[0] = width;
          var pAx = points[i - 2],
            pAy = points[i - 1];
          var pBx = points[i],
            pBy = points[i + 1];
          var pCx = points[i + 2],
            pCy = points[i + 3];
          var pDx = points[i + 4],
            pDy = points[i + 5];

          // make phantom points for the first and last segments
          // TODO adding 0.001 to avoid division by zero in the shader (I think), need a better solution
          if (i == 0) {
            pAx = 2 * pBx - pCx + 0.001;
            pAy = 2 * pBy - pCy + 0.001;
          }
          if (i == points.length - 4) {
            pDx = 2 * pCx - pBx + 0.001;
            pDy = 2 * pCy - pBy + 0.001;
          }
          var pointABView = this.pointAPointBBuffer.getView(_instance);
          pointABView[0] = pAx;
          pointABView[1] = pAy;
          pointABView[2] = pBx;
          pointABView[3] = pBy;
          var pointCDView = this.pointCPointDBuffer.getView(_instance);
          pointCDView[0] = pCx;
          pointCDView[1] = pCy;
          pointCDView[2] = pDx;
          pointCDView[3] = pDy;
          this.instanceCount++;
          if (this.instanceCount >= this.maxInstances) {
            this.endBatch();
          }
        }
      }
    }
  }, {
    key: "_getEdgePoints",
    value: function _getEdgePoints(edge) {
      var rs = edge._private.rscratch;

      // if bezier ctrl pts can not be calculated, then die
      if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
        // isNaN in case edge is impossible and browser bugs (e.g. safari)
        return;
      }
      var controlPoints = rs.allpts;
      if (controlPoints.length == 4) {
        return controlPoints;
      }
      var numSegments = this._getNumSegments(edge);
      return this._getCurveSegmentPoints(controlPoints, numSegments);
    }
  }, {
    key: "_getNumSegments",
    value: function _getNumSegments(edge) {
      // TODO Need a heuristic that decides how many segments to use. Factors to consider:
      // - edge width/length
      // - edge curvature (the more the curvature, the more segments)
      // - zoom level (more segments when zoomed in)
      // - number of visible edges (more segments when there are fewer edges)
      // - performance (fewer segments when performance is a concern)
      // - user configurable option(s)
      // note: number of segments must be less than the max number of instances
      // note: segments don't need to be evenly spaced out, it might make sense to have shorter segments nearer to the control points
      var numSegments = 15;
      return Math.min(Math.max(numSegments, 5), this.maxInstances);
    }
  }, {
    key: "_getCurveSegmentPoints",
    value: function _getCurveSegmentPoints(controlPoints, segments) {
      if (controlPoints.length == 4) {
        return controlPoints; // straight line
      }
      var curvePoints = Array((segments + 1) * 2);
      for (var i = 0; i <= segments; i++) {
        // the first and last points are the same as the first and last control points
        if (i == 0) {
          curvePoints[0] = controlPoints[0];
          curvePoints[1] = controlPoints[1];
        } else if (i == segments) {
          curvePoints[i * 2] = controlPoints[controlPoints.length - 2];
          curvePoints[i * 2 + 1] = controlPoints[controlPoints.length - 1];
        } else {
          var t = i / segments; // segments have equal length, its not strictly necessary to do it this way
          // pass in curvePoints to set the values in the array directly
          this._setCurvePoint(controlPoints, t, curvePoints, i * 2);
        }
      }
      return curvePoints;
    }
  }, {
    key: "_setCurvePoint",
    value: function _setCurvePoint(points, t, curvePoints, cpi) {
      if (points.length <= 2) {
        curvePoints[cpi] = points[0];
        curvePoints[cpi + 1] = points[1];
      } else {
        var newpoints = Array(points.length - 2);
        for (var i = 0; i < newpoints.length; i += 2) {
          var x = (1 - t) * points[i] + t * points[i + 2];
          var y = (1 - t) * points[i + 1] + t * points[i + 3];
          newpoints[i] = x;
          newpoints[i + 1] = y;
        }
        return this._setCurvePoint(newpoints, t, curvePoints, cpi);
      }
    }
  }, {
    key: "endBatch",
    value: function endBatch() {
      var gl = this.gl,
        vao = this.vao,
        vertexCount = this.vertexCount,
        count = this.instanceCount;
      if (count === 0) return;
      var program = this.renderTarget.picking ? this.pickingProgram : this.program;
      gl.useProgram(program);
      gl.bindVertexArray(vao);

      // buffer the attribute data
      var _iterator2 = _createForOfIteratorHelper(this.buffers),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var buffer = _step2.value;
          buffer.bufferSubData(count);
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      var atlases = this.batchManager.getAtlases();
      // must buffer before activating texture units
      for (var i = 0; i < atlases.length; i++) {
        atlases[i].bufferIfNeeded(gl);
      }
      // Activate all the texture units that we need
      for (var _i2 = 0; _i2 < atlases.length; _i2++) {
        gl.activeTexture(gl.TEXTURE0 + _i2);
        gl.bindTexture(gl.TEXTURE_2D, atlases[_i2].texture);
        gl.uniform1i(program.uTextures[_i2], _i2);
      }

      // Set the uniforms
      gl.uniform1f(program.uZoom, getEffectiveZoom(this.r));
      gl.uniformMatrix3fv(program.uPanZoomMatrix, false, this.panZoomMatrix);
      gl.uniform1i(program.uAtlasSize, this.batchManager.getAtlasSize());
      // set background color, needed for edge arrow color blending
      var webglBgColor = toWebGLColor(this.bgColor, 1);
      gl.uniform4fv(program.uBGColor, webglBgColor);

      // draw!
      gl.drawArraysInstanced(gl.TRIANGLES, 0, vertexCount, count);
      gl.bindVertexArray(null);
      gl.bindTexture(gl.TEXTURE_2D, null); // TODO is this right when having multiple texture units?

      if (this.debug) {
        this.batchDebugInfo.push({
          count: count,
          // instance count
          atlasCount: atlases.length
        });
      }

      // start the next batch, even if not needed
      this.startBatch();
    }
  }, {
    key: "getDebugInfo",
    value: function getDebugInfo() {
      var atlasInfo = this.atlasManager.getDebugInfo();
      var totalAtlases = atlasInfo.reduce(function (count, info) {
        return count + info.atlasCount;
      }, 0);
      var batchInfo = this.batchDebugInfo;
      var totalInstances = batchInfo.reduce(function (count, info) {
        return count + info.count;
      }, 0);
      return {
        atlasInfo: atlasInfo,
        totalAtlases: totalAtlases,
        wrappedCount: this.wrappedCount,
        simpleCount: this.simpleCount,
        batchCount: batchInfo.length,
        batchInfo: batchInfo,
        totalInstances: totalInstances
      };
    }
  }]);
}();

var CRp$4 = {};

/**
 * Initialize the WebGL rendering mode after the Canvas renderer has been initialized.
 */
CRp$4.initWebgl = function (opts, fns) {
  var r = this;
  var gl = r.data.contexts[r.WEBGL];

  // Set defaults and limits for configuration options.
  opts.bgColor = getBGColor(r);
  opts.webglTexSize = Math.min(opts.webglTexSize, gl.getParameter(gl.MAX_TEXTURE_SIZE));
  opts.webglTexRows = Math.min(opts.webglTexRows, 54);
  opts.webglTexRowsNodes = Math.min(opts.webglTexRowsNodes, 54);
  opts.webglBatchSize = Math.min(opts.webglBatchSize, 16384);
  opts.webglTexPerBatch = Math.min(opts.webglTexPerBatch, gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS));

  // Turn debug mode on or off.
  r.webglDebug = opts.webglDebug;
  r.webglDebugShowAtlases = opts.webglDebugShowAtlases;

  // Create offscreen framebuffer that stores the results when RENDER_TARGET.PICKING is enabled.
  // This is used to store the topmost element z-index for each pixel, which is used to tell whats under the mouse cursor point.
  r.pickingFrameBuffer = createPickingFrameBuffer(gl);
  r.pickingFrameBuffer.needsDraw = true;

  // Create an ElementDrawingWebGL instance wich is used to do the actual WebGL rendering.
  // This instance needs to be configured to draw various types of elements.
  r.drawing = new ElementDrawingWebGL(r, gl, opts);

  // Some functions that are used to configure ElementDrawingWebGL
  var getLabelRotation = function getLabelRotation(prop) {
    return function (ele) {
      return r.getTextAngle(ele, prop);
    };
  };
  var isLabelVisible = function isLabelVisible(prop) {
    return function (ele) {
      var label = ele.pstyle(prop);
      return label && label.value;
    };
  };
  var isLayerVisible = function isLayerVisible(prefix) {
    return function (node) {
      // prefix is 'overlay' or 'underlay'
      return node.pstyle("".concat(prefix, "-opacity")).value > 0;
    };
  };
  var getTexPickingMode = function getTexPickingMode(ele) {
    // tells when a label should be clickable
    var enabled = ele.pstyle('text-events').strValue === 'yes';
    return enabled ? TEX_PICKING_MODE.USE_BB : TEX_PICKING_MODE.IGNORE;
  };
  var getBBForSimpleShape = function getBBForSimpleShape(node) {
    // "simple" shapes need their BB to include border and padding
    var _node$position = node.position(),
      x = _node$position.x,
      y = _node$position.y;
    var w = node.outerWidth(); // includes border and padding
    var h = node.outerHeight();
    return {
      w: w,
      h: h,
      x1: x - w / 2,
      y1: y - h / 2
    };
  };

  // An AtlasCollection is a collection of Atlases that have the same configuraiton options.
  // Create one for node bodies and one for all types of labels.
  r.drawing.addAtlasCollection('node', {
    texRows: opts.webglTexRowsNodes
  });
  r.drawing.addAtlasCollection('label', {
    texRows: opts.webglTexRows
  });

  // Configure the different types of elements that can be rendered.

  // Node bodies can be rendered as textures or as "simple shapes". 
  // Simple shapes are preferred because they do not use texture memory.
  // Textures are required if the node body uses complex styles. 
  r.drawing.addTextureAtlasRenderType('node-body', {
    collection: 'node',
    getKey: fns.getStyleKey,
    getBoundingBox: fns.getElementBox,
    drawElement: fns.drawElement
  });
  r.drawing.addSimpleShapeRenderType('node-body', {
    getBoundingBox: getBBForSimpleShape,
    isSimple: isSimpleShape,
    shapeProps: {
      shape: 'shape',
      color: 'background-color',
      opacity: 'background-opacity',
      radius: 'corner-radius',
      border: true
    }
  });
  r.drawing.addSimpleShapeRenderType('node-overlay', {
    getBoundingBox: getBBForSimpleShape,
    isVisible: isLayerVisible('overlay'),
    shapeProps: {
      shape: 'overlay-shape',
      color: 'overlay-color',
      opacity: 'overlay-opacity',
      padding: 'overlay-padding',
      radius: 'overlay-corner-radius'
    }
  });
  r.drawing.addSimpleShapeRenderType('node-underlay', {
    getBoundingBox: getBBForSimpleShape,
    isVisible: isLayerVisible('underlay'),
    shapeProps: {
      shape: 'underlay-shape',
      color: 'underlay-color',
      opacity: 'underlay-opacity',
      padding: 'underlay-padding',
      radius: 'underlay-corner-radius'
    }
  });
  r.drawing.addTextureAtlasRenderType('label', {
    // node label or edge mid label
    collection: 'label',
    getTexPickingMode: getTexPickingMode,
    getKey: getStyleKeysForLabel(fns.getLabelKey, null),
    getBoundingBox: getBoundingBoxForLabel(fns.getLabelBox, null),
    drawClipped: true,
    drawElement: fns.drawLabel,
    getRotation: getLabelRotation(null),
    getRotationPoint: fns.getLabelRotationPoint,
    getRotationOffset: fns.getLabelRotationOffset,
    isVisible: isLabelVisible('label')
  });
  r.drawing.addTextureAtlasRenderType('edge-source-label', {
    collection: 'label',
    getTexPickingMode: getTexPickingMode,
    getKey: getStyleKeysForLabel(fns.getSourceLabelKey, 'source'),
    getBoundingBox: getBoundingBoxForLabel(fns.getSourceLabelBox, 'source'),
    drawClipped: true,
    drawElement: fns.drawSourceLabel,
    getRotation: getLabelRotation('source'),
    getRotationPoint: fns.getSourceLabelRotationPoint,
    getRotationOffset: fns.getSourceLabelRotationOffset,
    isVisible: isLabelVisible('source-label')
  });
  r.drawing.addTextureAtlasRenderType('edge-target-label', {
    collection: 'label',
    getTexPickingMode: getTexPickingMode,
    getKey: getStyleKeysForLabel(fns.getTargetLabelKey, 'target'),
    getBoundingBox: getBoundingBoxForLabel(fns.getTargetLabelBox, 'target'),
    drawClipped: true,
    drawElement: fns.drawTargetLabel,
    getRotation: getLabelRotation('target'),
    getRotationPoint: fns.getTargetLabelRotationPoint,
    getRotationOffset: fns.getTargetLabelRotationOffset,
    isVisible: isLabelVisible('target-label')
  });

  // Very simplistic way of triggering garbage collection, just use a timer.
  var setGCFlag = debounce(function () {
    console.log('garbage collect flag set');
    r.data.gc = true;
  }, 10000);

  // Event listener checks if style keys are no longer in use.
  r.onUpdateEleCalcs(function (willDraw, eles) {
    var gcNeeded = false;
    if (eles && eles.length > 0) {
      gcNeeded |= r.drawing.invalidate(eles);
    }
    if (gcNeeded) {
      setGCFlag();
    }
  });

  // "Override" certain functions in canvas and base renderer
  overrideCanvasRendererFunctions(r);
};
function getBGColor(r) {
  var container = r.cy.container();
  var cssColor = container && container.style && container.style.backgroundColor || 'white';
  return color2tuple(cssColor);
}
function getLabelLines(ele, prefix) {
  var rs = ele._private.rscratch;
  return getPrefixedProperty(rs, 'labelWrapCachedLines', prefix) || [];
}

/** 
 * Handle multi-line labels by rendering each line as a seperate texture.
 * That means each line needs its own style key.
 */
var getStyleKeysForLabel = function getStyleKeysForLabel(getKey, prefix) {
  return function (ele) {
    var key = getKey(ele);
    var lines = getLabelLines(ele, prefix);
    if (lines.length > 1) {
      return lines.map(function (line, index) {
        return "".concat(key, "_").concat(index);
      });
    }
    return key;
  };
};

/**
 * Need to create a separate bounding box for each line of a multi-line label.
 * Note that 'drawClipped: true' should be used with this.
 */
var getBoundingBoxForLabel = function getBoundingBoxForLabel(getBoundingBox, prefix) {
  return function (ele, styleKey) {
    var bb = getBoundingBox(ele);
    if (typeof styleKey === 'string') {
      var ui = styleKey.indexOf('_');
      if (ui > 0) {
        var lineIndex = Number(styleKey.substring(ui + 1));
        var lines = getLabelLines(ele, prefix);
        // Adjust the height and Y coordinate for one line of the label.
        var h = bb.h / lines.length;
        var yOffset = h * lineIndex;
        var y1 = bb.y1 + yOffset;
        // the yOffset is needed when rotating the label
        return {
          x1: bb.x1,
          w: bb.w,
          y1: y1,
          h: h,
          yOffset: yOffset
        };
      }
    }
    return bb;
  };
};

/**
 * Plug into the canvas renderer by dynamically overriding some of its functions.
 * This requires minimal changes to the canvas rendrerer.
 */
function overrideCanvasRendererFunctions(r) {
  {
    // Override the render function to call the webgl render function if the zoom level is appropriate
    var renderCanvas = r.render;
    r.render = function (options) {
      options = options || {};
      var cy = r.cy;
      if (r.webgl) {
        // If the zoom level is greater than the max zoom level, then disable webgl and switch back to 
        // the canvas renderer.
        if (cy.zoom() > maxZoom$1) {
          clearWebgl(r);
          renderCanvas.call(r, options);
        } else {
          clearCanvas(r);
          renderWebgl(r, options, RENDER_TARGET.SCREEN);
        }
      }
    };
  }
  {
    // Override the matchCanvasSize function to update the picking frame buffer size
    var baseFunc = r.matchCanvasSize;
    r.matchCanvasSize = function (container) {
      baseFunc.call(r, container);
      r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth, r.canvasHeight);
      r.pickingFrameBuffer.needsDraw = true;
    };
  }
  {
    // Override function to call the webgl version for picking.
    // Don't override r.getAllInBox() selction box picking, its not accurate enough with webgl
    r.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
      // the canvas version of this function is very slow on large graphs
      return findNearestElementsWebgl(r, x, y);
    };
  }
  {
    // need to know when the cached elements have changed so we can invalidate our caches
    var _baseFunc = r.invalidateCachedZSortedEles;
    r.invalidateCachedZSortedEles = function () {
      _baseFunc.call(r);
      r.pickingFrameBuffer.needsDraw = true;
    };
  }
  {
    // need to know when the cached elements have changed so we can invalidate our caches
    var _baseFunc2 = r.notify;
    r.notify = function (eventName, eles) {
      _baseFunc2.call(r, eventName, eles);
      if (eventName === 'viewport' || eventName === 'bounds') {
        r.pickingFrameBuffer.needsDraw = true;
      } else if (eventName === 'background') {
        // background image finished loading, need to redraw
        r.drawing.invalidate(eles, {
          type: 'node-body'
        });
      }
    };
  }
}
function clearWebgl(r) {
  var gl = r.data.contexts[r.WEBGL];
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
function clearCanvas(r) {
  // the CRp.clearCanvas() function doesn't take the transform into account
  var clear = function clear(context) {
    context.save();
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
    context.restore();
  };
  clear(r.data.contexts[r.NODE]);
  clear(r.data.contexts[r.DRAG]);
}
function createPanZoomMatrix(r) {
  var width = r.canvasWidth;
  var height = r.canvasHeight;
  var _util$getEffectivePan = getEffectivePanZoom(r),
    pan = _util$getEffectivePan.pan,
    zoom = _util$getEffectivePan.zoom;
  var transform = create();
  translate(transform, transform, [pan.x, pan.y]);
  scale(transform, transform, [zoom, zoom]);
  var projection$1 = create();
  projection(projection$1, width, height);
  var product = create();
  multiply(product, projection$1, transform);
  return product;
}
function setContextTransform(r, context) {
  var width = r.canvasWidth;
  var height = r.canvasHeight;
  var _util$getEffectivePan2 = getEffectivePanZoom(r),
    pan = _util$getEffectivePan2.pan,
    zoom = _util$getEffectivePan2.zoom;
  context.setTransform(1, 0, 0, 1, 0, 0);
  context.clearRect(0, 0, width, height);
  context.translate(pan.x, pan.y);
  context.scale(zoom, zoom);
}
function drawSelectionRectangle(r, options) {
  r.drawSelectionRectangle(options, function (context) {
    return setContextTransform(r, context);
  });
}
function drawAxes(r) {
  // for debgging
  var context = r.data.contexts[r.NODE];
  context.save();
  setContextTransform(r, context);
  context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
  context.beginPath();
  context.moveTo(-1e3, 0);
  context.lineTo(1000, 0);
  context.stroke();
  context.beginPath();
  context.moveTo(0, -1e3);
  context.lineTo(0, 1000);
  context.stroke();
  context.restore();
}
function drawAtlases(r) {
  // For debugging the atlases, this doesn't work for Atlases that are locked
  var draw = function draw(drawing, name, row) {
    var collection = drawing.atlasManager.getAtlasCollection(name);
    var context = r.data.contexts[r.NODE];
    var atlases = collection.atlases;
    for (var _i = 0; _i < atlases.length; _i++) {
      var atlas = atlases[_i];
      var canvas = atlas.canvas;
      if (canvas) {
        var w = canvas.width;
        var h = canvas.height;
        var x = w * _i;
        var y = canvas.height * row;
        var scale = 0.4;
        context.save();
        context.scale(scale, scale);
        context.drawImage(canvas, x, y);
        context.strokeStyle = 'black';
        context.rect(x, y, w, h);
        context.stroke();
        context.restore();
      }
    }
  };
  var i = 0;
  draw(r.drawing, 'node', i++);
  draw(r.drawing, 'label', i++);
}

/**
 * Returns the z-order index of elments under or very close to the mouse cursor point.
 * Arguments are in model coordinates.
 * (x1, y1) is top left corner
 * (x2, y2) is bottom right corner (optional)
 * Returns a Set of indexes.
 */
function getPickingIndexes(r, mX1, mY1, mX2, mY2) {
  var x, y, w, h;
  var _util$getEffectivePan3 = getEffectivePanZoom(r),
    pan = _util$getEffectivePan3.pan,
    zoom = _util$getEffectivePan3.zoom;
  {
    var _util$modelToRendered = modelToRenderedPosition(r, pan, zoom, mX1, mY1),
      _util$modelToRendered2 = _slicedToArray(_util$modelToRendered, 2),
      cX1 = _util$modelToRendered2[0],
      cY1 = _util$modelToRendered2[1];
    var t = 6; // should be even
    x = cX1 - t / 2;
    y = cY1 - t / 2;
    w = t;
    h = t;
  }
  if (w === 0 || h === 0) {
    return [];
  }
  var gl = r.data.contexts[r.WEBGL];
  gl.bindFramebuffer(gl.FRAMEBUFFER, r.pickingFrameBuffer);
  if (r.pickingFrameBuffer.needsDraw) {
    // Draw element z-indexes to the picking framebuffer
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    renderWebgl(r, null, RENDER_TARGET.PICKING);
    r.pickingFrameBuffer.needsDraw = false;
  }
  var n = w * h; // number of pixels to read
  var data = new Uint8Array(n * 4); // 4 bytes per pixel
  gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, data);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  var indexes = new Set();
  for (var i = 0; i < n; i++) {
    var pixel = data.slice(i * 4, i * 4 + 4);
    var index = vec4ToIndex(pixel) - 1; // The framebuffer is cleared with 0s, so z-indexes are offset by 1
    if (index >= 0) {
      indexes.add(index);
    }
  }
  return indexes;
}

/**
 * Cy.js: model coordinate y axis goes down
 */
function findNearestElementsWebgl(r, x, y) {
  // model coordinates
  var indexes = getPickingIndexes(r, x, y);
  var eles = r.getCachedZSortedEles();
  var node, edge;
  var _iterator = _createForOfIteratorHelper(indexes),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var index = _step.value;
      var ele = eles[index];
      if (!node && ele.isNode()) {
        node = ele;
      }
      if (!edge && ele.isEdge()) {
        edge = ele;
      }
      if (node && edge) {
        break;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return [node, edge].filter(Boolean);
}

/**
 * Draw one node or edge. 
 */
function drawEle(r, index, ele) {
  var drawing = r.drawing;
  index += 1; // 0 is used to clear the background, need to offset all z-indexes by one
  if (ele.isNode()) {
    drawing.drawNode(ele, index, 'node-underlay');
    drawing.drawNode(ele, index, 'node-body');
    drawing.drawTexture(ele, index, 'label');
    drawing.drawNode(ele, index, 'node-overlay');
  } else {
    drawing.drawEdgeLine(ele, index);
    drawing.drawEdgeArrow(ele, index, 'source');
    drawing.drawEdgeArrow(ele, index, 'target');
    drawing.drawTexture(ele, index, 'label');
    drawing.drawTexture(ele, index, 'edge-source-label');
    drawing.drawTexture(ele, index, 'edge-target-label');
  }
}

/**
 * Render one frame.
 */
function renderWebgl(r, options, renderTarget) {
  var start;
  if (r.webglDebug) {
    start = performance.now(); // eslint-disable-line no-undef
  }
  var drawing = r.drawing;
  var eleCount = 0;
  if (renderTarget.screen) {
    if (r.data.canvasNeedsRedraw[r.SELECT_BOX]) {
      drawSelectionRectangle(r, options);
    }
  }

  // see drawing-elements.js drawCachedElement()
  if (r.data.canvasNeedsRedraw[r.NODE] || renderTarget.picking) {
    var gl = r.data.contexts[r.WEBGL];
    if (renderTarget.screen) {
      gl.clearColor(0, 0, 0, 0); // background color
      gl.enable(gl.BLEND); // enable alpha blending of colors
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // webgl colors use premultiplied alpha
    } else {
      gl.disable(gl.BLEND); // don't blend z-order index values! they are not colors
    }
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    var panZoomMatrix = createPanZoomMatrix(r);
    var eles = r.getCachedZSortedEles();
    eleCount = eles.length;
    drawing.startFrame(panZoomMatrix, renderTarget);
    if (renderTarget.screen) {
      for (var i = 0; i < eles.nondrag.length; i++) {
        drawEle(r, i, eles.nondrag[i]);
      }
      for (var _i2 = 0; _i2 < eles.drag.length; _i2++) {
        drawEle(r, _i2, eles.drag[_i2]);
      }
    } else if (renderTarget.picking) {
      for (var _i3 = 0; _i3 < eles.length; _i3++) {
        drawEle(r, _i3, eles[_i3]);
      }
    }
    drawing.endFrame();
    if (renderTarget.screen && r.webglDebugShowAtlases) {
      drawAxes(r);
      drawAtlases(r);
    }
    r.data.canvasNeedsRedraw[r.NODE] = false;
    r.data.canvasNeedsRedraw[r.DRAG] = false;
  }
  if (r.webglDebug) {
    // eslint-disable-next-line no-undef
    var end = performance.now();
    var compact = false;
    var time = Math.ceil(end - start);
    var debugInfo = drawing.getDebugInfo();
    var report = ["".concat(eleCount, " elements"), "".concat(debugInfo.totalInstances, " instances"), "".concat(debugInfo.batchCount, " batches"), "".concat(debugInfo.totalAtlases, " atlases"), "".concat(debugInfo.wrappedCount, " wrapped textures"), "".concat(debugInfo.simpleCount, " simple shapes")].join(', ');
    if (compact) {
      console.log("WebGL (".concat(renderTarget.name, ") - time ").concat(time, "ms, ").concat(report));
    } else {
      console.log("WebGL (".concat(renderTarget.name, ") - frame time ").concat(time, "ms"));
      console.log('Totals:');
      console.log("  ".concat(report));
      console.log('Texture Atlases Used:');
      var atlasInfo = debugInfo.atlasInfo;
      var _iterator2 = _createForOfIteratorHelper(atlasInfo),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var info = _step2.value;
          console.log("  ".concat(info.type, ": ").concat(info.keyCount, " keys, ").concat(info.atlasCount, " atlases"));
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      console.log('');
    }
  }
  if (r.data.gc) {
    console.log('Garbage Collect!');
    r.data.gc = false;
    drawing.gc();
  }
}

var CRp$3 = {};

// @O Polygon drawing
CRp$3.drawPolygonPath = function (context, x, y, width, height, points) {
  var halfW = width / 2;
  var halfH = height / 2;
  if (context.beginPath) {
    context.beginPath();
  }
  context.moveTo(x + halfW * points[0], y + halfH * points[1]);
  for (var i = 1; i < points.length / 2; i++) {
    context.lineTo(x + halfW * points[i * 2], y + halfH * points[i * 2 + 1]);
  }
  context.closePath();
};
CRp$3.drawRoundPolygonPath = function (context, x, y, width, height, points, corners) {
  corners.forEach(function (corner) {
    return drawPreparedRoundCorner(context, corner);
  });
  context.closePath();
};

// Round rectangle drawing
CRp$3.drawRoundRectanglePath = function (context, x, y, width, height, radius) {
  var halfWidth = width / 2;
  var halfHeight = height / 2;
  var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : Math.min(radius, halfHeight, halfWidth);
  if (context.beginPath) {
    context.beginPath();
  }

  // Start at top middle
  context.moveTo(x, y - halfHeight);
  // Arc from middle top to right side
  context.arcTo(x + halfWidth, y - halfHeight, x + halfWidth, y, cornerRadius);
  // Arc from right side to bottom
  context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  // Arc from bottom to left side
  context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  // Arc from left side to topBorder
  context.arcTo(x - halfWidth, y - halfHeight, x, y - halfHeight, cornerRadius);
  // Join line
  context.lineTo(x, y - halfHeight);
  context.closePath();
};
CRp$3.drawBottomRoundRectanglePath = function (context, x, y, width, height, radius) {
  var halfWidth = width / 2;
  var halfHeight = height / 2;
  var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  if (context.beginPath) {
    context.beginPath();
  }

  // Start at top middle
  context.moveTo(x, y - halfHeight);
  context.lineTo(x + halfWidth, y - halfHeight);
  context.lineTo(x + halfWidth, y);
  context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  context.lineTo(x - halfWidth, y - halfHeight);
  context.lineTo(x, y - halfHeight);
  context.closePath();
};
CRp$3.drawCutRectanglePath = function (context, x, y, width, height, points, corners) {
  var halfWidth = width / 2;
  var halfHeight = height / 2;
  var cornerLength = corners === 'auto' ? getCutRectangleCornerLength() : corners;
  if (context.beginPath) {
    context.beginPath();
  }
  context.moveTo(x - halfWidth + cornerLength, y - halfHeight);
  context.lineTo(x + halfWidth - cornerLength, y - halfHeight);
  context.lineTo(x + halfWidth, y - halfHeight + cornerLength);
  context.lineTo(x + halfWidth, y + halfHeight - cornerLength);
  context.lineTo(x + halfWidth - cornerLength, y + halfHeight);
  context.lineTo(x - halfWidth + cornerLength, y + halfHeight);
  context.lineTo(x - halfWidth, y + halfHeight - cornerLength);
  context.lineTo(x - halfWidth, y - halfHeight + cornerLength);
  context.closePath();
};
CRp$3.drawBarrelPath = function (context, x, y, width, height) {
  var halfWidth = width / 2;
  var halfHeight = height / 2;
  var xBegin = x - halfWidth;
  var xEnd = x + halfWidth;
  var yBegin = y - halfHeight;
  var yEnd = y + halfHeight;
  var barrelCurveConstants = getBarrelCurveConstants(width, height);
  var wOffset = barrelCurveConstants.widthOffset;
  var hOffset = barrelCurveConstants.heightOffset;
  var ctrlPtXOffset = barrelCurveConstants.ctrlPtOffsetPct * wOffset;
  if (context.beginPath) {
    context.beginPath();
  }
  context.moveTo(xBegin, yBegin + hOffset);
  context.lineTo(xBegin, yEnd - hOffset);
  context.quadraticCurveTo(xBegin + ctrlPtXOffset, yEnd, xBegin + wOffset, yEnd);
  context.lineTo(xEnd - wOffset, yEnd);
  context.quadraticCurveTo(xEnd - ctrlPtXOffset, yEnd, xEnd, yEnd - hOffset);
  context.lineTo(xEnd, yBegin + hOffset);
  context.quadraticCurveTo(xEnd - ctrlPtXOffset, yBegin, xEnd - wOffset, yBegin);
  context.lineTo(xBegin + wOffset, yBegin);
  context.quadraticCurveTo(xBegin + ctrlPtXOffset, yBegin, xBegin, yBegin + hOffset);
  context.closePath();
};
var sin0 = Math.sin(0);
var cos0 = Math.cos(0);
var sin = {};
var cos = {};
var ellipseStepSize = Math.PI / 40;
for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  sin[i] = Math.sin(i);
  cos[i] = Math.cos(i);
}
CRp$3.drawEllipsePath = function (context, centerX, centerY, width, height) {
  if (context.beginPath) {
    context.beginPath();
  }
  if (context.ellipse) {
    context.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, 2 * Math.PI);
  } else {
    var xPos, yPos;
    var rw = width / 2;
    var rh = height / 2;
    for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
      xPos = centerX - rw * sin[i] * sin0 + rw * cos[i] * cos0;
      yPos = centerY + rh * cos[i] * sin0 + rh * sin[i] * cos0;
      if (i === 0) {
        context.moveTo(xPos, yPos);
      } else {
        context.lineTo(xPos, yPos);
      }
    }
  }
  context.closePath();
};

/* global atob, ArrayBuffer, Uint8Array, Blob */

var CRp$2 = {};
CRp$2.createBuffer = function (w, h) {
  var buffer = document.createElement('canvas'); // eslint-disable-line no-undef
  buffer.width = w;
  buffer.height = h;
  return [buffer, buffer.getContext('2d')];
};
CRp$2.bufferCanvasImage = function (options) {
  var cy = this.cy;
  var eles = cy.mutableElements();
  var bb = eles.boundingBox();
  var ctrRect = this.findContainerClientCoords();
  var width = options.full ? Math.ceil(bb.w) : ctrRect[2];
  var height = options.full ? Math.ceil(bb.h) : ctrRect[3];
  var specdMaxDims = number$1(options.maxWidth) || number$1(options.maxHeight);
  var pxRatio = this.getPixelRatio();
  var scale = 1;
  if (options.scale !== undefined) {
    width *= options.scale;
    height *= options.scale;
    scale = options.scale;
  } else if (specdMaxDims) {
    var maxScaleW = Infinity;
    var maxScaleH = Infinity;
    if (number$1(options.maxWidth)) {
      maxScaleW = scale * options.maxWidth / width;
    }
    if (number$1(options.maxHeight)) {
      maxScaleH = scale * options.maxHeight / height;
    }
    scale = Math.min(maxScaleW, maxScaleH);
    width *= scale;
    height *= scale;
  }
  if (!specdMaxDims) {
    width *= pxRatio;
    height *= pxRatio;
    scale *= pxRatio;
  }
  var buffCanvas = document.createElement('canvas'); // eslint-disable-line no-undef

  buffCanvas.width = width;
  buffCanvas.height = height;
  buffCanvas.style.width = width + 'px';
  buffCanvas.style.height = height + 'px';
  var buffCxt = buffCanvas.getContext('2d');

  // Rasterize the layers, but only if container has nonzero size
  if (width > 0 && height > 0) {
    buffCxt.clearRect(0, 0, width, height);
    buffCxt.globalCompositeOperation = 'source-over';
    var zsortedEles = this.getCachedZSortedEles();
    if (options.full) {
      // draw the full bounds of the graph
      buffCxt.translate(-bb.x1 * scale, -bb.y1 * scale);
      buffCxt.scale(scale, scale);
      this.drawElements(buffCxt, zsortedEles);
      buffCxt.scale(1 / scale, 1 / scale);
      buffCxt.translate(bb.x1 * scale, bb.y1 * scale);
    } else {
      // draw the current view
      var pan = cy.pan();
      var translation = {
        x: pan.x * scale,
        y: pan.y * scale
      };
      scale *= cy.zoom();
      buffCxt.translate(translation.x, translation.y);
      buffCxt.scale(scale, scale);
      this.drawElements(buffCxt, zsortedEles);
      buffCxt.scale(1 / scale, 1 / scale);
      buffCxt.translate(-translation.x, -translation.y);
    }

    // need to fill bg at end like this in order to fill cleared transparent pixels in jpgs
    if (options.bg) {
      buffCxt.globalCompositeOperation = 'destination-over';
      buffCxt.fillStyle = options.bg;
      buffCxt.rect(0, 0, width, height);
      buffCxt.fill();
    }
  }
  return buffCanvas;
};
function b64ToBlob(b64, mimeType) {
  var bytes = atob(b64);
  var buff = new ArrayBuffer(bytes.length);
  var buffUint8 = new Uint8Array(buff);
  for (var i = 0; i < bytes.length; i++) {
    buffUint8[i] = bytes.charCodeAt(i);
  }
  return new Blob([buff], {
    type: mimeType
  });
}
function b64UriToB64(b64uri) {
  var i = b64uri.indexOf(',');
  return b64uri.substr(i + 1);
}
function output(options, canvas, mimeType) {
  var getB64Uri = function getB64Uri() {
    return canvas.toDataURL(mimeType, options.quality);
  };
  switch (options.output) {
    case 'blob-promise':
      return new Promise$1(function (resolve, reject) {
        try {
          canvas.toBlob(function (blob) {
            if (blob != null) {
              resolve(blob);
            } else {
              reject(new Error('`canvas.toBlob()` sent a null value in its callback'));
            }
          }, mimeType, options.quality);
        } catch (err) {
          reject(err);
        }
      });
    case 'blob':
      return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);
    case 'base64':
      return b64UriToB64(getB64Uri());
    case 'base64uri':
    default:
      return getB64Uri();
  }
}
CRp$2.png = function (options) {
  return output(options, this.bufferCanvasImage(options), 'image/png');
};
CRp$2.jpg = function (options) {
  return output(options, this.bufferCanvasImage(options), 'image/jpeg');
};

var CRp$1 = {};
CRp$1.nodeShapeImpl = function (name, context, centerX, centerY, width, height, points, corners) {
  switch (name) {
    case 'ellipse':
      return this.drawEllipsePath(context, centerX, centerY, width, height);
    case 'polygon':
      return this.drawPolygonPath(context, centerX, centerY, width, height, points);
    case 'round-polygon':
      return this.drawRoundPolygonPath(context, centerX, centerY, width, height, points, corners);
    case 'roundrectangle':
    case 'round-rectangle':
      return this.drawRoundRectanglePath(context, centerX, centerY, width, height, corners);
    case 'cutrectangle':
    case 'cut-rectangle':
      return this.drawCutRectanglePath(context, centerX, centerY, width, height, points, corners);
    case 'bottomroundrectangle':
    case 'bottom-round-rectangle':
      return this.drawBottomRoundRectanglePath(context, centerX, centerY, width, height, corners);
    case 'barrel':
      return this.drawBarrelPath(context, centerX, centerY, width, height);
  }
};

var CR = CanvasRenderer;
var CRp = CanvasRenderer.prototype;
CRp.CANVAS_LAYERS = 3;
//
CRp.SELECT_BOX = 0;
CRp.DRAG = 1;
CRp.NODE = 2;
CRp.WEBGL = 3;
CRp.CANVAS_TYPES = ['2d', '2d', '2d', 'webgl2'];
CRp.BUFFER_COUNT = 3;
//
CRp.TEXTURE_BUFFER = 0;
CRp.MOTIONBLUR_BUFFER_NODE = 1;
CRp.MOTIONBLUR_BUFFER_DRAG = 2;
function CanvasRenderer(options) {
  var r = this;
  var containerWindow = r.cy.window();
  var document = containerWindow.document;
  if (options.webgl) {
    CRp.CANVAS_LAYERS = r.CANVAS_LAYERS = 4;
    console.log('webgl rendering enabled');
  }
  r.data = {
    canvases: new Array(CRp.CANVAS_LAYERS),
    contexts: new Array(CRp.CANVAS_LAYERS),
    canvasNeedsRedraw: new Array(CRp.CANVAS_LAYERS),
    bufferCanvases: new Array(CRp.BUFFER_COUNT),
    bufferContexts: new Array(CRp.CANVAS_LAYERS)
  };
  var tapHlOffAttr = '-webkit-tap-highlight-color';
  var tapHlOffStyle = 'rgba(0,0,0,0)';
  r.data.canvasContainer = document.createElement('div'); // eslint-disable-line no-undef
  var containerStyle = r.data.canvasContainer.style;
  r.data.canvasContainer.style[tapHlOffAttr] = tapHlOffStyle;
  containerStyle.position = 'relative';
  containerStyle.zIndex = '0';
  containerStyle.overflow = 'hidden';
  var container = options.cy.container();
  container.appendChild(r.data.canvasContainer);
  container.style[tapHlOffAttr] = tapHlOffStyle;
  var styleMap = {
    '-webkit-user-select': 'none',
    '-moz-user-select': '-moz-none',
    'user-select': 'none',
    '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',
    'outline-style': 'none'
  };
  if (ms()) {
    styleMap['-ms-touch-action'] = 'none';
    styleMap['touch-action'] = 'none';
  }
  for (var i = 0; i < CRp.CANVAS_LAYERS; i++) {
    var canvas = r.data.canvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
    var type = CRp.CANVAS_TYPES[i];
    r.data.contexts[i] = canvas.getContext(type);
    if (!r.data.contexts[i]) {
      error('Could not create canvas of type ' + type);
    }
    Object.keys(styleMap).forEach(function (k) {
      canvas.style[k] = styleMap[k];
    });
    canvas.style.position = 'absolute';
    canvas.setAttribute('data-id', 'layer' + i);
    canvas.style.zIndex = String(CRp.CANVAS_LAYERS - i);
    r.data.canvasContainer.appendChild(canvas);
    r.data.canvasNeedsRedraw[i] = false;
  }
  r.data.topCanvas = r.data.canvases[0];
  r.data.canvases[CRp.NODE].setAttribute('data-id', 'layer' + CRp.NODE + '-node');
  r.data.canvases[CRp.SELECT_BOX].setAttribute('data-id', 'layer' + CRp.SELECT_BOX + '-selectbox');
  r.data.canvases[CRp.DRAG].setAttribute('data-id', 'layer' + CRp.DRAG + '-drag');
  if (r.data.canvases[CRp.WEBGL]) {
    r.data.canvases[CRp.WEBGL].setAttribute('data-id', 'layer' + CRp.WEBGL + '-webgl');
  }
  for (var i = 0; i < CRp.BUFFER_COUNT; i++) {
    r.data.bufferCanvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
    r.data.bufferContexts[i] = r.data.bufferCanvases[i].getContext('2d');
    r.data.bufferCanvases[i].style.position = 'absolute';
    r.data.bufferCanvases[i].setAttribute('data-id', 'buffer' + i);
    r.data.bufferCanvases[i].style.zIndex = String(-i - 1);
    r.data.bufferCanvases[i].style.visibility = 'hidden';
    //r.data.canvasContainer.appendChild(r.data.bufferCanvases[i]);
  }
  r.pathsEnabled = true;
  var emptyBb = makeBoundingBox();
  var getBoxCenter = function getBoxCenter(bb) {
    return {
      x: (bb.x1 + bb.x2) / 2,
      y: (bb.y1 + bb.y2) / 2
    };
  };
  var getCenterOffset = function getCenterOffset(bb) {
    return {
      x: -bb.w / 2,
      y: -bb.h / 2
    };
  };
  var backgroundTimestampHasChanged = function backgroundTimestampHasChanged(ele) {
    var _p = ele[0]._private;
    var same = _p.oldBackgroundTimestamp === _p.backgroundTimestamp;
    return !same;
  };
  var getStyleKey = function getStyleKey(ele) {
    return ele[0]._private.nodeKey;
  };
  var getLabelKey = function getLabelKey(ele) {
    return ele[0]._private.labelStyleKey;
  };
  var getSourceLabelKey = function getSourceLabelKey(ele) {
    return ele[0]._private.sourceLabelStyleKey;
  };
  var getTargetLabelKey = function getTargetLabelKey(ele) {
    return ele[0]._private.targetLabelStyleKey;
  };
  var drawElement = function drawElement(context, ele, bb, scaledLabelShown, useEleOpacity) {
    return r.drawElement(context, ele, bb, false, false, useEleOpacity);
  };
  var drawLabel = function drawLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
    return r.drawElementText(context, ele, bb, scaledLabelShown, 'main', useEleOpacity);
  };
  var drawSourceLabel = function drawSourceLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
    return r.drawElementText(context, ele, bb, scaledLabelShown, 'source', useEleOpacity);
  };
  var drawTargetLabel = function drawTargetLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
    return r.drawElementText(context, ele, bb, scaledLabelShown, 'target', useEleOpacity);
  };
  var getElementBox = function getElementBox(ele) {
    ele.boundingBox();
    return ele[0]._private.bodyBounds;
  };
  var getLabelBox = function getLabelBox(ele) {
    ele.boundingBox();
    return ele[0]._private.labelBounds.main || emptyBb;
  };
  var getSourceLabelBox = function getSourceLabelBox(ele) {
    ele.boundingBox();
    return ele[0]._private.labelBounds.source || emptyBb;
  };
  var getTargetLabelBox = function getTargetLabelBox(ele) {
    ele.boundingBox();
    return ele[0]._private.labelBounds.target || emptyBb;
  };
  var isLabelVisibleAtScale = function isLabelVisibleAtScale(ele, scaledLabelShown) {
    return scaledLabelShown;
  };
  var getElementRotationPoint = function getElementRotationPoint(ele) {
    return getBoxCenter(getElementBox(ele));
  };
  var addTextMargin = function addTextMargin(prefix, pt, ele) {
    var pre = prefix ? prefix + '-' : '';
    return {
      x: pt.x + ele.pstyle(pre + 'text-margin-x').pfValue,
      y: pt.y + ele.pstyle(pre + 'text-margin-y').pfValue
    };
  };
  var getRsPt = function getRsPt(ele, x, y) {
    var rs = ele[0]._private.rscratch;
    return {
      x: rs[x],
      y: rs[y]
    };
  };
  var getLabelRotationPoint = function getLabelRotationPoint(ele) {
    return addTextMargin('', getRsPt(ele, 'labelX', 'labelY'), ele);
  };
  var getSourceLabelRotationPoint = function getSourceLabelRotationPoint(ele) {
    return addTextMargin('source', getRsPt(ele, 'sourceLabelX', 'sourceLabelY'), ele);
  };
  var getTargetLabelRotationPoint = function getTargetLabelRotationPoint(ele) {
    return addTextMargin('target', getRsPt(ele, 'targetLabelX', 'targetLabelY'), ele);
  };
  var getElementRotationOffset = function getElementRotationOffset(ele) {
    return getCenterOffset(getElementBox(ele));
  };
  var getSourceLabelRotationOffset = function getSourceLabelRotationOffset(ele) {
    return getCenterOffset(getSourceLabelBox(ele));
  };
  var getTargetLabelRotationOffset = function getTargetLabelRotationOffset(ele) {
    return getCenterOffset(getTargetLabelBox(ele));
  };
  var getLabelRotationOffset = function getLabelRotationOffset(ele) {
    var bb = getLabelBox(ele);
    var p = getCenterOffset(getLabelBox(ele));
    if (ele.isNode()) {
      switch (ele.pstyle('text-halign').value) {
        case 'left':
          p.x = -bb.w - (bb.leftPad || 0);
          break;
        case 'right':
          p.x = -(bb.rightPad || 0);
          break;
      }
      switch (ele.pstyle('text-valign').value) {
        case 'top':
          p.y = -bb.h - (bb.topPad || 0);
          break;
        case 'bottom':
          p.y = -(bb.botPad || 0);
          break;
      }
    }
    return p;
  };
  var eleTxrCache = r.data.eleTxrCache = new ElementTextureCache(r, {
    getKey: getStyleKey,
    doesEleInvalidateKey: backgroundTimestampHasChanged,
    drawElement: drawElement,
    getBoundingBox: getElementBox,
    getRotationPoint: getElementRotationPoint,
    getRotationOffset: getElementRotationOffset,
    allowEdgeTxrCaching: false,
    allowParentTxrCaching: false
  });
  var lblTxrCache = r.data.lblTxrCache = new ElementTextureCache(r, {
    getKey: getLabelKey,
    drawElement: drawLabel,
    getBoundingBox: getLabelBox,
    getRotationPoint: getLabelRotationPoint,
    getRotationOffset: getLabelRotationOffset,
    isVisible: isLabelVisibleAtScale
  });
  var slbTxrCache = r.data.slbTxrCache = new ElementTextureCache(r, {
    getKey: getSourceLabelKey,
    drawElement: drawSourceLabel,
    getBoundingBox: getSourceLabelBox,
    getRotationPoint: getSourceLabelRotationPoint,
    getRotationOffset: getSourceLabelRotationOffset,
    isVisible: isLabelVisibleAtScale
  });
  var tlbTxrCache = r.data.tlbTxrCache = new ElementTextureCache(r, {
    getKey: getTargetLabelKey,
    drawElement: drawTargetLabel,
    getBoundingBox: getTargetLabelBox,
    getRotationPoint: getTargetLabelRotationPoint,
    getRotationOffset: getTargetLabelRotationOffset,
    isVisible: isLabelVisibleAtScale
  });
  var lyrTxrCache = r.data.lyrTxrCache = new LayeredTextureCache(r);
  r.onUpdateEleCalcs(function invalidateTextureCaches(willDraw, eles) {
    // each cache should check for sub-key diff to see that the update affects that cache particularly
    eleTxrCache.invalidateElements(eles);
    lblTxrCache.invalidateElements(eles);
    slbTxrCache.invalidateElements(eles);
    tlbTxrCache.invalidateElements(eles);

    // any change invalidates the layers
    lyrTxrCache.invalidateElements(eles);

    // update the old bg timestamp so diffs can be done in the ele txr caches
    for (var _i = 0; _i < eles.length; _i++) {
      var _p = eles[_i]._private;
      _p.oldBackgroundTimestamp = _p.backgroundTimestamp;
    }
  });
  var refineInLayers = function refineInLayers(reqs) {
    for (var i = 0; i < reqs.length; i++) {
      lyrTxrCache.enqueueElementRefinement(reqs[i].ele);
    }
  };
  eleTxrCache.onDequeue(refineInLayers);
  lblTxrCache.onDequeue(refineInLayers);
  slbTxrCache.onDequeue(refineInLayers);
  tlbTxrCache.onDequeue(refineInLayers);
  if (options.webgl) {
    r.initWebgl(options, {
      getStyleKey: getStyleKey,
      getLabelKey: getLabelKey,
      getSourceLabelKey: getSourceLabelKey,
      getTargetLabelKey: getTargetLabelKey,
      drawElement: drawElement,
      drawLabel: drawLabel,
      drawSourceLabel: drawSourceLabel,
      drawTargetLabel: drawTargetLabel,
      getElementBox: getElementBox,
      getLabelBox: getLabelBox,
      getSourceLabelBox: getSourceLabelBox,
      getTargetLabelBox: getTargetLabelBox,
      getElementRotationPoint: getElementRotationPoint,
      getElementRotationOffset: getElementRotationOffset,
      getLabelRotationPoint: getLabelRotationPoint,
      getSourceLabelRotationPoint: getSourceLabelRotationPoint,
      getTargetLabelRotationPoint: getTargetLabelRotationPoint,
      getLabelRotationOffset: getLabelRotationOffset,
      getSourceLabelRotationOffset: getSourceLabelRotationOffset,
      getTargetLabelRotationOffset: getTargetLabelRotationOffset
    });
  }
}
CRp.redrawHint = function (group, bool) {
  var r = this;
  switch (group) {
    case 'eles':
      r.data.canvasNeedsRedraw[CRp.NODE] = bool;
      break;
    case 'drag':
      r.data.canvasNeedsRedraw[CRp.DRAG] = bool;
      break;
    case 'select':
      r.data.canvasNeedsRedraw[CRp.SELECT_BOX] = bool;
      break;
    case 'gc':
      r.data.gc = true;
      break;
  }
};

// whether to use Path2D caching for drawing
var pathsImpld = typeof Path2D !== 'undefined';
CRp.path2dEnabled = function (on) {
  if (on === undefined) {
    return this.pathsEnabled;
  }
  this.pathsEnabled = on ? true : false;
};
CRp.usePaths = function () {
  return pathsImpld && this.pathsEnabled;
};
CRp.setImgSmoothing = function (context, bool) {
  if (context.imageSmoothingEnabled != null) {
    context.imageSmoothingEnabled = bool;
  } else {
    context.webkitImageSmoothingEnabled = bool;
    context.mozImageSmoothingEnabled = bool;
    context.msImageSmoothingEnabled = bool;
  }
};
CRp.getImgSmoothing = function (context) {
  if (context.imageSmoothingEnabled != null) {
    return context.imageSmoothingEnabled;
  } else {
    return context.webkitImageSmoothingEnabled || context.mozImageSmoothingEnabled || context.msImageSmoothingEnabled;
  }
};
CRp.makeOffscreenCanvas = function (width, height) {
  var canvas;
  if ((typeof OffscreenCanvas === "undefined" ? "undefined" : _typeof(OffscreenCanvas)) !== ("undefined" )) {
    canvas = new OffscreenCanvas(width, height);
  } else {
    var containerWindow = this.cy.window();
    var document = containerWindow.document;
    canvas = document.createElement('canvas'); // eslint-disable-line no-undef
    canvas.width = width;
    canvas.height = height;
  }
  return canvas;
};
[CRp$b, CRp$a, CRp$9, CRp$8, CRp$7, CRp$6, CRp$5, CRp$4, CRp$3, CRp$2, CRp$1].forEach(function (props) {
  extend(CRp, props);
});

var renderer = [{
  name: 'null',
  impl: NullRenderer
}, {
  name: 'base',
  impl: BR
}, {
  name: 'canvas',
  impl: CR
}];

var incExts = [{
  type: 'layout',
  extensions: layout
}, {
  type: 'renderer',
  extensions: renderer
}];

// registered extensions to cytoscape, indexed by name
var extensions = {};

// registered modules for extensions, indexed by name
var modules = {};
function setExtension(type, name, registrant) {
  var ext = registrant;
  var overrideErr = function overrideErr(field) {
    warn('Can not register `' + name + '` for `' + type + '` since `' + field + '` already exists in the prototype and can not be overridden');
  };
  if (type === 'core') {
    if (Core.prototype[name]) {
      return overrideErr(name);
    } else {
      Core.prototype[name] = registrant;
    }
  } else if (type === 'collection') {
    if (Collection.prototype[name]) {
      return overrideErr(name);
    } else {
      Collection.prototype[name] = registrant;
    }
  } else if (type === 'layout') {
    // fill in missing layout functions in the prototype

    var Layout = function Layout(options) {
      this.options = options;
      registrant.call(this, options);

      // make sure layout has _private for use w/ std apis like .on()
      if (!plainObject(this._private)) {
        this._private = {};
      }
      this._private.cy = options.cy;
      this._private.listeners = [];
      this.createEmitter();
    };
    var layoutProto = Layout.prototype = Object.create(registrant.prototype);
    var optLayoutFns = [];
    for (var i = 0; i < optLayoutFns.length; i++) {
      var fnName = optLayoutFns[i];
      layoutProto[fnName] = layoutProto[fnName] || function () {
        return this;
      };
    }

    // either .start() or .run() is defined, so autogen the other
    if (layoutProto.start && !layoutProto.run) {
      layoutProto.run = function () {
        this.start();
        return this;
      };
    } else if (!layoutProto.start && layoutProto.run) {
      layoutProto.start = function () {
        this.run();
        return this;
      };
    }
    var regStop = registrant.prototype.stop;
    layoutProto.stop = function () {
      var opts = this.options;
      if (opts && opts.animate) {
        var anis = this.animations;
        if (anis) {
          for (var _i = 0; _i < anis.length; _i++) {
            anis[_i].stop();
          }
        }
      }
      if (regStop) {
        regStop.call(this);
      } else {
        this.emit('layoutstop');
      }
      return this;
    };
    if (!layoutProto.destroy) {
      layoutProto.destroy = function () {
        return this;
      };
    }
    layoutProto.cy = function () {
      return this._private.cy;
    };
    var getCy = function getCy(layout) {
      return layout._private.cy;
    };
    var emitterOpts = {
      addEventFields: function addEventFields(layout, evt) {
        evt.layout = layout;
        evt.cy = getCy(layout);
        evt.target = layout;
      },
      bubble: function bubble() {
        return true;
      },
      parent: function parent(layout) {
        return getCy(layout);
      }
    };
    extend(layoutProto, {
      createEmitter: function createEmitter() {
        this._private.emitter = new Emitter(emitterOpts, this);
        return this;
      },
      emitter: function emitter() {
        return this._private.emitter;
      },
      on: function on(evt, cb) {
        this.emitter().on(evt, cb);
        return this;
      },
      one: function one(evt, cb) {
        this.emitter().one(evt, cb);
        return this;
      },
      once: function once(evt, cb) {
        this.emitter().one(evt, cb);
        return this;
      },
      removeListener: function removeListener(evt, cb) {
        this.emitter().removeListener(evt, cb);
        return this;
      },
      removeAllListeners: function removeAllListeners() {
        this.emitter().removeAllListeners();
        return this;
      },
      emit: function emit(evt, params) {
        this.emitter().emit(evt, params);
        return this;
      }
    });
    define.eventAliasesOn(layoutProto);
    ext = Layout; // replace with our wrapped layout
  } else if (type === 'renderer' && name !== 'null' && name !== 'base') {
    // user registered renderers inherit from base

    var BaseRenderer = getExtension('renderer', 'base');
    var bProto = BaseRenderer.prototype;
    var RegistrantRenderer = registrant;
    var rProto = registrant.prototype;
    var Renderer = function Renderer() {
      BaseRenderer.apply(this, arguments);
      RegistrantRenderer.apply(this, arguments);
    };
    var proto = Renderer.prototype;
    for (var pName in bProto) {
      var pVal = bProto[pName];
      var existsInR = rProto[pName] != null;
      if (existsInR) {
        return overrideErr(pName);
      }
      proto[pName] = pVal; // take impl from base
    }
    for (var _pName in rProto) {
      proto[_pName] = rProto[_pName]; // take impl from registrant
    }
    bProto.clientFunctions.forEach(function (name) {
      proto[name] = proto[name] || function () {
        error('Renderer does not implement `renderer.' + name + '()` on its prototype');
      };
    });
    ext = Renderer;
  } else if (type === '__proto__' || type === 'constructor' || type === 'prototype') {
    // to avoid potential prototype pollution
    return error(type + ' is an illegal type to be registered, possibly lead to prototype pollutions');
  }
  return setMap({
    map: extensions,
    keys: [type, name],
    value: ext
  });
}
function getExtension(type, name) {
  return getMap({
    map: extensions,
    keys: [type, name]
  });
}
function setModule(type, name, moduleType, moduleName, registrant) {
  return setMap({
    map: modules,
    keys: [type, name, moduleType, moduleName],
    value: registrant
  });
}
function getModule(type, name, moduleType, moduleName) {
  return getMap({
    map: modules,
    keys: [type, name, moduleType, moduleName]
  });
}
var extension = function extension() {
  // e.g. extension('renderer', 'svg')
  if (arguments.length === 2) {
    return getExtension.apply(null, arguments);
  }

  // e.g. extension('renderer', 'svg', { ... })
  else if (arguments.length === 3) {
    return setExtension.apply(null, arguments);
  }

  // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse')
  else if (arguments.length === 4) {
    return getModule.apply(null, arguments);
  }

  // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse', { ... })
  else if (arguments.length === 5) {
    return setModule.apply(null, arguments);
  } else {
    error('Invalid extension access syntax');
  }
};

// allows a core instance to access extensions internally
Core.prototype.extension = extension;

// included extensions
incExts.forEach(function (group) {
  group.extensions.forEach(function (ext) {
    setExtension(group.type, ext.name, ext.impl);
  });
});

// a dummy stylesheet object that doesn't need a reference to the core
// (useful for init)
var _Stylesheet = function Stylesheet() {
  if (!(this instanceof _Stylesheet)) {
    return new _Stylesheet();
  }
  this.length = 0;
};
var sheetfn = _Stylesheet.prototype;
sheetfn.instanceString = function () {
  return 'stylesheet';
};

// just store the selector to be parsed later
sheetfn.selector = function (selector) {
  var i = this.length++;
  this[i] = {
    selector: selector,
    properties: []
  };
  return this; // chaining
};

// just store the property to be parsed later
sheetfn.css = function (name, value) {
  var i = this.length - 1;
  if (string(name)) {
    this[i].properties.push({
      name: name,
      value: value
    });
  } else if (plainObject(name)) {
    var map = name;
    var propNames = Object.keys(map);
    for (var j = 0; j < propNames.length; j++) {
      var key = propNames[j];
      var mapVal = map[key];
      if (mapVal == null) {
        continue;
      }
      var prop = _Style.properties[key] || _Style.properties[dash2camel(key)];
      if (prop == null) {
        continue;
      }
      var _name = prop.name;
      var _value = mapVal;
      this[i].properties.push({
        name: _name,
        value: _value
      });
    }
  }
  return this; // chaining
};
sheetfn.style = sheetfn.css;

// generate a real style object from the dummy stylesheet
sheetfn.generateStyle = function (cy) {
  var style = new _Style(cy);
  return this.appendToStyle(style);
};

// append a dummy stylesheet object on a real style object
sheetfn.appendToStyle = function (style) {
  for (var i = 0; i < this.length; i++) {
    var context = this[i];
    var selector = context.selector;
    var props = context.properties;
    style.selector(selector); // apply selector

    for (var j = 0; j < props.length; j++) {
      var prop = props[j];
      style.css(prop.name, prop.value); // apply property
    }
  }
  return style;
};

var version = "3.33.0";

var cytoscape = function cytoscape(options) {
  // if no options specified, use default
  if (options === undefined) {
    options = {};
  }

  // create instance
  if (plainObject(options)) {
    return new Core(options);
  }

  // allow for registration of extensions
  else if (string(options)) {
    return extension.apply(extension, arguments);
  }
};

// e.g. cytoscape.use( require('cytoscape-foo'), bar )
cytoscape.use = function (ext) {
  var args = Array.prototype.slice.call(arguments, 1); // args to pass to ext

  args.unshift(cytoscape); // cytoscape is first arg to ext

  ext.apply(null, args);
  return this;
};
cytoscape.warnings = function (bool) {
  return warnings(bool);
};

// replaced by build system
cytoscape.version = version;

// expose public apis (mostly for extensions)
cytoscape.stylesheet = cytoscape.Stylesheet = _Stylesheet;




/***/ }),

/***/ 300:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.I18nLabel = void 0;
var I18nLabel;
(function (I18nLabel) {
    I18nLabel["Close_Tab"] = "Close";
    I18nLabel["Close_Tabset"] = "Close tabset";
    I18nLabel["Move_Tab"] = "Move: ";
    I18nLabel["Move_Tabset"] = "Move tabset";
    I18nLabel["Maximize"] = "Maximize tabset";
    I18nLabel["Restore"] = "Restore tabset";
    I18nLabel["Float_Tab"] = "Show selected tab in floating window";
    I18nLabel["Overflow_Menu_Tooltip"] = "Hidden tabs";
    I18nLabel["Floating_Window_Message"] = "This panel is shown in a floating window";
    I18nLabel["Floating_Window_Show_Window"] = "Show window";
    I18nLabel["Floating_Window_Dock_Window"] = "Dock window";
    I18nLabel["Error_rendering_component"] = "Error rendering component";
})(I18nLabel = exports.I18nLabel || (exports.I18nLabel = {}));
//# sourceMappingURL=I18nLabel.js.map

/***/ }),

/***/ 343:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isAuxMouseEvent = exports.hideElement = exports.getRenderStateEx = void 0;
const React = __webpack_require__(6540);
/** @internal */
function getRenderStateEx(layout, node, iconFactory, titleFactory, iconAngle) {
    let leadingContent = iconFactory ? iconFactory(node) : undefined;
    let titleContent = node.getName();
    let name = node.getName();
    if (iconAngle === undefined) {
        iconAngle = 0;
    }
    function isTitleObject(obj) {
        return obj.titleContent !== undefined;
    }
    if (titleFactory !== undefined) {
        const titleObj = titleFactory(node);
        if (titleObj !== undefined) {
            if (typeof titleObj === "string") {
                titleContent = titleObj;
                name = titleObj;
            }
            else if (isTitleObject(titleObj)) {
                titleContent = titleObj.titleContent;
                name = titleObj.name;
            }
            else {
                titleContent = titleObj;
            }
        }
    }
    if (leadingContent === undefined && node.getIcon() !== undefined) {
        if (iconAngle !== 0) {
            leadingContent = React.createElement("img", { style: { width: "1em", height: "1em", transform: "rotate(" + iconAngle + "deg)" }, src: node.getIcon(), alt: "leadingContent" });
        }
        else {
            leadingContent = React.createElement("img", { style: { width: "1em", height: "1em" }, src: node.getIcon(), alt: "leadingContent" });
        }
    }
    let buttons = [];
    // allow customization of leading contents (icon) and contents
    const renderState = { leading: leadingContent, content: titleContent, name, buttons };
    layout.customizeTab(node, renderState);
    node._setRenderedName(renderState.name);
    return renderState;
}
exports.getRenderStateEx = getRenderStateEx;
/** @internal */
function hideElement(style, useVisibility) {
    if (useVisibility) {
        style.visibility = "hidden";
    }
    else {
        style.display = "none";
    }
}
exports.hideElement = hideElement;
/** @internal */
function isAuxMouseEvent(event) {
    let auxEvent = false;
    if (event.nativeEvent instanceof MouseEvent) {
        if (event.nativeEvent.button !== 0 || event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) {
            auxEvent = true;
        }
    }
    return auxEvent;
}
exports.isAuxMouseEvent = isAuxMouseEvent;
//# sourceMappingURL=Utils.js.map

/***/ }),

/***/ 883:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DragDrop = void 0;
const Rect_1 = __webpack_require__(2530);
/** @internal */
const canUseDOM = !!(typeof window !== "undefined" && window.document && window.document.createElement);
class DragDrop {
    /** @internal */
    constructor() {
        /** @internal */
        this._manualGlassManagement = false;
        /** @internal */
        this._startX = 0;
        /** @internal */
        this._startY = 0;
        /** @internal */
        this._dragDepth = 0;
        /** @internal */
        this._glassShowing = false;
        /** @internal */
        this._dragging = false;
        /** @internal */
        this._active = false; // drag and drop is in progress, can be used on ios to prevent body scrolling (see demo)
        if (canUseDOM) {
            // check for serverside rendering
            this._glass = document.createElement("div");
            this._glass.style.zIndex = "998";
            this._glass.style.backgroundColor = "transparent";
            this._glass.style.outline = "none";
        }
        this._defaultGlassCursor = "default";
        this._onMouseMove = this._onMouseMove.bind(this);
        this._onMouseUp = this._onMouseUp.bind(this);
        this._onKeyPress = this._onKeyPress.bind(this);
        this._onDragCancel = this._onDragCancel.bind(this);
        this._onDragEnter = this._onDragEnter.bind(this);
        this._onDragLeave = this._onDragLeave.bind(this);
        this.resizeGlass = this.resizeGlass.bind(this);
        this._lastClick = 0;
        this._clickX = 0;
        this._clickY = 0;
    }
    // if you add the glass pane then you should remove it
    addGlass(fCancel) {
        var _a;
        if (!this._glassShowing) {
            if (!this._document) {
                this._document = window.document;
            }
            if (!this._rootElement) {
                this._rootElement = this._document.body;
            }
            this.resizeGlass();
            (_a = this._document.defaultView) === null || _a === void 0 ? void 0 : _a.addEventListener('resize', this.resizeGlass);
            this._document.body.appendChild(this._glass);
            this._glass.tabIndex = -1;
            this._glass.focus();
            this._glass.addEventListener("keydown", this._onKeyPress);
            this._glass.addEventListener("dragenter", this._onDragEnter, { passive: false });
            this._glass.addEventListener("dragover", this._onMouseMove, { passive: false });
            this._glass.addEventListener("dragleave", this._onDragLeave, { passive: false });
            this._glassShowing = true;
            this._fDragCancel = fCancel;
            this._manualGlassManagement = false;
        }
        else {
            // second call to addGlass (via dragstart)
            this._manualGlassManagement = true;
        }
    }
    resizeGlass() {
        const glassRect = Rect_1.Rect.fromElement(this._rootElement);
        glassRect.positionElement(this._glass, "fixed");
    }
    hideGlass() {
        var _a;
        if (this._glassShowing) {
            this._document.body.removeChild(this._glass);
            (_a = this._document.defaultView) === null || _a === void 0 ? void 0 : _a.removeEventListener('resize', this.resizeGlass);
            this._glassShowing = false;
            this._document = undefined;
            this._rootElement = undefined;
            this.setGlassCursorOverride(undefined);
        }
    }
    /** @internal */
    _updateGlassCursor() {
        var _a;
        this._glass.style.cursor = (_a = this._glassCursorOverride) !== null && _a !== void 0 ? _a : this._defaultGlassCursor;
    }
    /** @internal */
    _setDefaultGlassCursor(cursor) {
        this._defaultGlassCursor = cursor;
        this._updateGlassCursor();
    }
    setGlassCursorOverride(cursor) {
        this._glassCursorOverride = cursor;
        this._updateGlassCursor();
    }
    startDrag(event, fDragStart, fDragMove, fDragEnd, fDragCancel, fClick, fDblClick, currentDocument, rootElement) {
        // prevent 'duplicate' action (mouse event for same action as previous touch event (a fix for ios))
        if (event && this._lastEvent && this._lastEvent.type.startsWith("touch") && event.type.startsWith("mouse") && event.timeStamp - this._lastEvent.timeStamp < 500) {
            return;
        }
        if (this._dragging) {
            return;
        }
        this._lastEvent = event;
        if (currentDocument) {
            this._document = currentDocument;
        }
        else {
            this._document = window.document;
        }
        if (rootElement) {
            this._rootElement = rootElement;
        }
        else {
            this._rootElement = this._document.body;
        }
        const posEvent = this._getLocationEvent(event);
        this.addGlass(fDragCancel);
        if (event) {
            this._startX = posEvent.clientX;
            this._startY = posEvent.clientY;
            if (!window.matchMedia || window.matchMedia("(pointer: fine)").matches) {
                this._setDefaultGlassCursor(getComputedStyle(event.target).cursor);
            }
            this._stopPropagation(event);
            this._preventDefault(event);
        }
        else {
            this._startX = 0;
            this._startY = 0;
            this._setDefaultGlassCursor("default");
        }
        this._dragging = false;
        this._fDragStart = fDragStart;
        this._fDragMove = fDragMove;
        this._fDragEnd = fDragEnd;
        this._fDragCancel = fDragCancel;
        this._fClick = fClick;
        this._fDblClick = fDblClick;
        this._active = true;
        if ((event === null || event === void 0 ? void 0 : event.type) === 'dragenter') {
            this._dragDepth = 1;
            this._rootElement.addEventListener("dragenter", this._onDragEnter, { passive: false });
            this._rootElement.addEventListener("dragover", this._onMouseMove, { passive: false });
            this._rootElement.addEventListener("dragleave", this._onDragLeave, { passive: false });
            this._document.addEventListener("dragend", this._onDragCancel, { passive: false });
            this._document.addEventListener("drop", this._onMouseUp, { passive: false });
        }
        else {
            this._document.addEventListener("mouseup", this._onMouseUp, { passive: false });
            this._document.addEventListener("mousemove", this._onMouseMove, { passive: false });
            this._document.addEventListener("touchend", this._onMouseUp, { passive: false });
            this._document.addEventListener("touchmove", this._onMouseMove, { passive: false });
        }
    }
    isDragging() {
        return this._dragging;
    }
    isActive() {
        return this._active;
    }
    toString() {
        const rtn = "(DragDrop: " + "startX=" + this._startX + ", startY=" + this._startY + ", dragging=" + this._dragging + ")";
        return rtn;
    }
    /** @internal */
    _onKeyPress(event) {
        if (event.code === 'Escape') {
            // esc
            this._onDragCancel();
        }
    }
    /** @internal */
    _onDragCancel() {
        this._rootElement.removeEventListener("dragenter", this._onDragEnter);
        this._rootElement.removeEventListener("dragover", this._onMouseMove);
        this._rootElement.removeEventListener("dragleave", this._onDragLeave);
        this._document.removeEventListener("dragend", this._onDragCancel);
        this._document.removeEventListener("drop", this._onMouseUp);
        this._document.removeEventListener("mousemove", this._onMouseMove);
        this._document.removeEventListener("mouseup", this._onMouseUp);
        this._document.removeEventListener("touchend", this._onMouseUp);
        this._document.removeEventListener("touchmove", this._onMouseMove);
        this.hideGlass();
        if (this._fDragCancel !== undefined) {
            this._fDragCancel(this._dragging);
        }
        this._dragging = false;
        this._active = false;
    }
    /** @internal */
    _getLocationEvent(event) {
        let posEvent = event;
        if (event && event.touches) {
            posEvent = event.touches[0];
        }
        return posEvent;
    }
    /** @internal */
    _getLocationEventEnd(event) {
        let posEvent = event;
        if (event.changedTouches) {
            posEvent = event.changedTouches[0];
        }
        return posEvent;
    }
    /** @internal */
    _stopPropagation(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        }
    }
    /** @internal */
    _preventDefault(event) {
        if (event.preventDefault && event.cancelable) {
            event.preventDefault();
        }
        return event;
    }
    /** @internal */
    _onMouseMove(event) {
        this._lastEvent = event;
        const posEvent = this._getLocationEvent(event);
        this._stopPropagation(event);
        this._preventDefault(event);
        if (!this._dragging && (Math.abs(this._startX - posEvent.clientX) > 5 || Math.abs(this._startY - posEvent.clientY) > 5)) {
            this._dragging = true;
            if (this._fDragStart) {
                this._setDefaultGlassCursor("move");
                this._dragging = this._fDragStart({ clientX: this._startX, clientY: this._startY });
            }
        }
        if (this._dragging) {
            if (this._fDragMove) {
                this._fDragMove(posEvent);
            }
        }
        return false;
    }
    /** @internal */
    _onMouseUp(event) {
        this._lastEvent = event;
        const posEvent = this._getLocationEventEnd(event);
        this._stopPropagation(event);
        this._preventDefault(event);
        this._active = false;
        this._rootElement.removeEventListener("dragenter", this._onDragEnter);
        this._rootElement.removeEventListener("dragover", this._onMouseMove);
        this._rootElement.removeEventListener("dragleave", this._onDragLeave);
        this._document.removeEventListener("dragend", this._onDragCancel);
        this._document.removeEventListener("drop", this._onMouseUp);
        this._document.removeEventListener("mousemove", this._onMouseMove);
        this._document.removeEventListener("mouseup", this._onMouseUp);
        this._document.removeEventListener("touchend", this._onMouseUp);
        this._document.removeEventListener("touchmove", this._onMouseMove);
        if (!this._manualGlassManagement) {
            this.hideGlass();
        }
        if (this._dragging) {
            this._dragging = false;
            if (this._fDragEnd) {
                this._fDragEnd(event);
            }
            // dump("set dragging = false\n");
        }
        else {
            if (this._fDragCancel) {
                this._fDragCancel(this._dragging);
            }
            if (Math.abs(this._startX - posEvent.clientX) <= 5 && Math.abs(this._startY - posEvent.clientY) <= 5) {
                let isDoubleClick = false;
                const clickTime = new Date().getTime();
                // check for double click
                if (Math.abs(this._clickX - posEvent.clientX) <= 5 && Math.abs(this._clickY - posEvent.clientY) <= 5) {
                    if (clickTime - this._lastClick < 500) {
                        if (this._fDblClick) {
                            this._fDblClick(event);
                            isDoubleClick = true;
                        }
                    }
                }
                if (!isDoubleClick && this._fClick) {
                    this._fClick(event);
                }
                this._lastClick = clickTime;
                this._clickX = posEvent.clientX;
                this._clickY = posEvent.clientY;
            }
        }
        return false;
    }
    /** @internal */
    _onDragEnter(event) {
        this._preventDefault(event);
        this._stopPropagation(event);
        this._dragDepth++;
        return false;
    }
    /** @internal */
    _onDragLeave(event) {
        this._preventDefault(event);
        this._stopPropagation(event);
        this._dragDepth--;
        if (this._dragDepth <= 0) {
            this._onDragCancel();
        }
        return false;
    }
}
exports.DragDrop = DragDrop;
DragDrop.instance = new DragDrop();
//# sourceMappingURL=DragDrop.js.map

/***/ }),

/***/ 1200:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Action = void 0;
class Action {
    constructor(type, data) {
        this.type = type;
        this.data = data;
    }
}
exports.Action = Action;
//# sourceMappingURL=Action.js.map

/***/ }),

/***/ 1287:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
var react__WEBPACK_IMPORTED_MODULE_0___namespace_cache;
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   i: function() { return /* binding */ useInsertionEffectWithLayoutFallback; },
/* harmony export */   s: function() { return /* binding */ useInsertionEffectAlwaysWithSyncFallback; }
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6540);


var syncFallback = function syncFallback(create) {
  return create();
};

var useInsertionEffect = /*#__PURE__*/ (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_0__, 2)))['useInsertion' + 'Effect'] ? /*#__PURE__*/ (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_0__, 2)))['useInsertion' + 'Effect'] : false;
var useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback;
var useInsertionEffectWithLayoutFallback = useInsertionEffect || react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect;




/***/ }),

/***/ 1479:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  A: function() { return /* binding */ styled; }
});

// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__(8168);
// EXTERNAL MODULE: ./node_modules/@emotion/react/dist/emotion-element-f0de968e.browser.esm.js
var emotion_element_f0de968e_browser_esm = __webpack_require__(4684);
// EXTERNAL MODULE: ./node_modules/@emotion/serialize/dist/emotion-serialize.esm.js + 2 modules
var emotion_serialize_esm = __webpack_require__(3174);
// EXTERNAL MODULE: ./node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js
var emotion_use_insertion_effect_with_fallbacks_browser_esm = __webpack_require__(1287);
// EXTERNAL MODULE: ./node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js
var emotion_utils_browser_esm = __webpack_require__(41);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(6540);
// EXTERNAL MODULE: ./node_modules/@emotion/memoize/dist/emotion-memoize.esm.js
var emotion_memoize_esm = __webpack_require__(6289);
;// ./node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js


// eslint-disable-next-line no-undef
var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|fetchpriority|fetchPriority|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23

var isPropValid = /* #__PURE__ */(0,emotion_memoize_esm/* default */.A)(function (prop) {
  return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
  /* o */
  && prop.charCodeAt(1) === 110
  /* n */
  && prop.charCodeAt(2) < 91;
}
/* Z+1 */
);



;// ./node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js








var isDevelopment = false;

var testOmitPropsOnStringTag = isPropValid;

var testOmitPropsOnComponent = function testOmitPropsOnComponent(key) {
  return key !== 'theme';
};

var getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) {
  return typeof tag === 'string' && // 96 is one less than the char code
  // for "a" so this is checking that
  // it's a lowercase character
  tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;
};
var composeShouldForwardProps = function composeShouldForwardProps(tag, options, isReal) {
  var shouldForwardProp;

  if (options) {
    var optionsShouldForwardProp = options.shouldForwardProp;
    shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName) {
      return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName);
    } : optionsShouldForwardProp;
  }

  if (typeof shouldForwardProp !== 'function' && isReal) {
    shouldForwardProp = tag.__emotion_forwardProp;
  }

  return shouldForwardProp;
};

var Insertion = function Insertion(_ref) {
  var cache = _ref.cache,
      serialized = _ref.serialized,
      isStringTag = _ref.isStringTag;
  (0,emotion_utils_browser_esm/* registerStyles */.SF)(cache, serialized, isStringTag);
  (0,emotion_use_insertion_effect_with_fallbacks_browser_esm/* useInsertionEffectAlwaysWithSyncFallback */.s)(function () {
    return (0,emotion_utils_browser_esm/* insertStyles */.sk)(cache, serialized, isStringTag);
  });

  return null;
};

var createStyled = function createStyled(tag, options) {

  var isReal = tag.__emotion_real === tag;
  var baseTag = isReal && tag.__emotion_base || tag;
  var identifierName;
  var targetClassName;

  if (options !== undefined) {
    identifierName = options.label;
    targetClassName = options.target;
  }

  var shouldForwardProp = composeShouldForwardProps(tag, options, isReal);
  var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);
  var shouldUseAs = !defaultShouldForwardProp('as');
  return function () {
    // eslint-disable-next-line prefer-rest-params
    var args = arguments;
    var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];

    if (identifierName !== undefined) {
      styles.push("label:" + identifierName + ";");
    }

    if (args[0] == null || args[0].raw === undefined) {
      // eslint-disable-next-line prefer-spread
      styles.push.apply(styles, args);
    } else {
      var templateStringsArr = args[0];

      styles.push(templateStringsArr[0]);
      var len = args.length;
      var i = 1;

      for (; i < len; i++) {

        styles.push(args[i], templateStringsArr[i]);
      }
    }

    var Styled = (0,emotion_element_f0de968e_browser_esm.w)(function (props, cache, ref) {
      var FinalTag = shouldUseAs && props.as || baseTag;
      var className = '';
      var classInterpolations = [];
      var mergedProps = props;

      if (props.theme == null) {
        mergedProps = {};

        for (var key in props) {
          mergedProps[key] = props[key];
        }

        mergedProps.theme = react.useContext(emotion_element_f0de968e_browser_esm.T);
      }

      if (typeof props.className === 'string') {
        className = (0,emotion_utils_browser_esm/* getRegisteredStyles */.Rk)(cache.registered, classInterpolations, props.className);
      } else if (props.className != null) {
        className = props.className + " ";
      }

      var serialized = (0,emotion_serialize_esm/* serializeStyles */.J)(styles.concat(classInterpolations), cache.registered, mergedProps);
      className += cache.key + "-" + serialized.name;

      if (targetClassName !== undefined) {
        className += " " + targetClassName;
      }

      var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;
      var newProps = {};

      for (var _key in props) {
        if (shouldUseAs && _key === 'as') continue;

        if (finalShouldForwardProp(_key)) {
          newProps[_key] = props[_key];
        }
      }

      newProps.className = className;

      if (ref) {
        newProps.ref = ref;
      }

      return /*#__PURE__*/react.createElement(react.Fragment, null, /*#__PURE__*/react.createElement(Insertion, {
        cache: cache,
        serialized: serialized,
        isStringTag: typeof FinalTag === 'string'
      }), /*#__PURE__*/react.createElement(FinalTag, newProps));
    });
    Styled.displayName = identifierName !== undefined ? identifierName : "Styled(" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + ")";
    Styled.defaultProps = tag.defaultProps;
    Styled.__emotion_real = Styled;
    Styled.__emotion_base = baseTag;
    Styled.__emotion_styles = styles;
    Styled.__emotion_forwardProp = shouldForwardProp;
    Object.defineProperty(Styled, 'toString', {
      value: function value() {
        if (targetClassName === undefined && isDevelopment) {
          return 'NO_COMPONENT_SELECTOR';
        }

        return "." + targetClassName;
      }
    });

    Styled.withComponent = function (nextTag, nextOptions) {
      var newStyled = createStyled(nextTag, (0,esm_extends/* default */.A)({}, options, nextOptions, {
        shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true)
      }));
      return newStyled.apply(void 0, styles);
    };

    return Styled;
  };
};



;// ./node_modules/@emotion/styled/dist/emotion-styled.browser.esm.js









var tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];

// bind it to avoid mutating the original function
var styled = createStyled.bind(null);
tags.forEach(function (tagName) {
  styled[tagName] = styled(tagName);
});




/***/ }),

/***/ 1480:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BorderNode = void 0;
const Attribute_1 = __webpack_require__(46);
const AttributeDefinitions_1 = __webpack_require__(6874);
const DockLocation_1 = __webpack_require__(8324);
const DropInfo_1 = __webpack_require__(4017);
const Orientation_1 = __webpack_require__(1648);
const Rect_1 = __webpack_require__(2530);
const Types_1 = __webpack_require__(6643);
const Node_1 = __webpack_require__(7618);
const SplitterNode_1 = __webpack_require__(6169);
const TabNode_1 = __webpack_require__(8171);
const Utils_1 = __webpack_require__(2429);
class BorderNode extends Node_1.Node {
    /** @internal */
    static _fromJson(json, model) {
        const location = DockLocation_1.DockLocation.getByName(json.location);
        const border = new BorderNode(location, json, model);
        if (json.children) {
            border._children = json.children.map((jsonChild) => {
                const child = TabNode_1.TabNode._fromJson(jsonChild, model);
                child._setParent(border);
                return child;
            });
        }
        return border;
    }
    /** @internal */
    static _createAttributeDefinitions() {
        const attributeDefinitions = new AttributeDefinitions_1.AttributeDefinitions();
        attributeDefinitions.add("type", BorderNode.TYPE, true).setType(Attribute_1.Attribute.STRING).setFixed();
        attributeDefinitions.add("selected", -1).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("show", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("config", undefined).setType("any");
        attributeDefinitions.addInherited("barSize", "borderBarSize").setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.addInherited("enableDrop", "borderEnableDrop").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("className", "borderClassName").setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.addInherited("autoSelectTabWhenOpen", "borderAutoSelectTabWhenOpen").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("autoSelectTabWhenClosed", "borderAutoSelectTabWhenClosed").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("size", "borderSize").setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.addInherited("minSize", "borderMinSize").setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.addInherited("enableAutoHide", "borderEnableAutoHide").setType(Attribute_1.Attribute.BOOLEAN);
        return attributeDefinitions;
    }
    /** @internal */
    constructor(location, json, model) {
        super(model);
        /** @internal */
        this._adjustedSize = 0;
        /** @internal */
        this._calculatedBorderBarSize = 0;
        this._location = location;
        this._drawChildren = [];
        this._attributes.id = `border_${location.getName()}`;
        BorderNode._attributeDefinitions.fromJson(json, this._attributes);
        model._addNode(this);
    }
    getLocation() {
        return this._location;
    }
    getTabHeaderRect() {
        return this._tabHeaderRect;
    }
    getRect() {
        return this._tabHeaderRect;
    }
    getContentRect() {
        return this._contentRect;
    }
    isEnableDrop() {
        return this._getAttr("enableDrop");
    }
    isAutoSelectTab(whenOpen) {
        if (whenOpen == null) {
            whenOpen = this.getSelected() !== -1;
        }
        if (whenOpen) {
            return this._getAttr("autoSelectTabWhenOpen");
        }
        else {
            return this._getAttr("autoSelectTabWhenClosed");
        }
    }
    getClassName() {
        return this._getAttr("className");
    }
    /** @internal */
    calcBorderBarSize(metrics) {
        const barSize = this._getAttr("barSize");
        if (barSize !== 0) {
            // its defined
            this._calculatedBorderBarSize = barSize;
        }
        else {
            this._calculatedBorderBarSize = metrics.borderBarSize;
        }
    }
    getBorderBarSize() {
        return this._calculatedBorderBarSize;
    }
    getSize() {
        const defaultSize = this._getAttr("size");
        const selected = this.getSelected();
        if (selected === -1) {
            return defaultSize;
        }
        else {
            const tabNode = this._children[selected];
            const tabBorderSize = (this._location._orientation === Orientation_1.Orientation.HORZ) ? tabNode._getAttr("borderWidth") : tabNode._getAttr("borderHeight");
            if (tabBorderSize === -1) {
                return defaultSize;
            }
            else {
                return tabBorderSize;
            }
        }
    }
    getMinSize() {
        return this._getAttr("minSize");
    }
    getSelected() {
        return this._attributes.selected;
    }
    getSelectedNode() {
        if (this.getSelected() !== -1) {
            return this._children[this.getSelected()];
        }
        return undefined;
    }
    getOrientation() {
        return this._location.getOrientation();
    }
    /**
     * Returns the config attribute that can be used to store node specific data that
     * WILL be saved to the json. The config attribute should be changed via the action Actions.updateNodeAttributes rather
     * than directly, for example:
     * this.state.model.doAction(
     *   FlexLayout.Actions.updateNodeAttributes(node.getId(), {config:myConfigObject}));
     */
    getConfig() {
        return this._attributes.config;
    }
    isMaximized() {
        return false;
    }
    isShowing() {
        const show = this._attributes.show;
        if (show) {
            if (this._model._getShowHiddenBorder() !== this._location && this.isAutoHide() && this._children.length === 0) {
                return false;
            }
            return true;
        }
        else {
            return false;
        }
    }
    isAutoHide() {
        return this._getAttr("enableAutoHide");
    }
    /** @internal */
    _setSelected(index) {
        this._attributes.selected = index;
    }
    /** @internal */
    _setSize(pos) {
        const selected = this.getSelected();
        if (selected === -1) {
            this._attributes.size = pos;
        }
        else {
            const tabNode = this._children[selected];
            const tabBorderSize = (this._location._orientation === Orientation_1.Orientation.HORZ) ? tabNode._getAttr("borderWidth") : tabNode._getAttr("borderHeight");
            if (tabBorderSize === -1) {
                this._attributes.size = pos;
            }
            else {
                if (this._location._orientation === Orientation_1.Orientation.HORZ) {
                    tabNode._setBorderWidth(pos);
                }
                else {
                    tabNode._setBorderHeight(pos);
                }
            }
        }
    }
    /** @internal */
    _updateAttrs(json) {
        BorderNode._attributeDefinitions.update(json, this._attributes);
    }
    /** @internal */
    _getDrawChildren() {
        return this._drawChildren;
    }
    /** @internal */
    _setAdjustedSize(size) {
        this._adjustedSize = size;
    }
    /** @internal */
    _getAdjustedSize() {
        return this._adjustedSize;
    }
    /** @internal */
    _layoutBorderOuter(outer, metrics) {
        this.calcBorderBarSize(metrics);
        const split1 = this._location.split(outer, this.getBorderBarSize()); // split border outer
        this._tabHeaderRect = split1.start;
        return split1.end;
    }
    /** @internal */
    _layoutBorderInner(inner, metrics) {
        this._drawChildren = [];
        const location = this._location;
        const split1 = location.split(inner, this._adjustedSize + this._model.getSplitterSize()); // split off tab contents
        const split2 = location.reflect().split(split1.start, this._model.getSplitterSize()); // split contents into content and splitter
        this._contentRect = split2.end;
        for (let i = 0; i < this._children.length; i++) {
            const child = this._children[i];
            child._layout(this._contentRect, metrics);
            child._setVisible(i === this.getSelected());
            this._drawChildren.push(child);
        }
        if (this.getSelected() === -1) {
            return inner;
        }
        else {
            const newSplitter = new SplitterNode_1.SplitterNode(this._model);
            newSplitter._setParent(this);
            newSplitter._setRect(split2.start);
            this._drawChildren.push(newSplitter);
            return split1.end;
        }
    }
    /** @internal */
    _remove(node) {
        const removedIndex = this._removeChild(node);
        if (this.getSelected() !== -1) {
            (0, Utils_1.adjustSelectedIndex)(this, removedIndex);
        }
    }
    /** @internal */
    canDrop(dragNode, x, y) {
        if (dragNode.getType() !== TabNode_1.TabNode.TYPE) {
            return undefined;
        }
        let dropInfo;
        const dockLocation = DockLocation_1.DockLocation.CENTER;
        if (this._tabHeaderRect.contains(x, y)) {
            if (this._location._orientation === Orientation_1.Orientation.VERT) {
                if (this._children.length > 0) {
                    let child = this._children[0];
                    let childRect = child.getTabRect();
                    const childY = childRect.y;
                    const childHeight = childRect.height;
                    let pos = this._tabHeaderRect.x;
                    let childCenter = 0;
                    for (let i = 0; i < this._children.length; i++) {
                        child = this._children[i];
                        childRect = child.getTabRect();
                        childCenter = childRect.x + childRect.width / 2;
                        if (x >= pos && x < childCenter) {
                            const outlineRect = new Rect_1.Rect(childRect.x - 2, childY, 3, childHeight);
                            dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, i, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                            break;
                        }
                        pos = childCenter;
                    }
                    if (dropInfo == null) {
                        const outlineRect = new Rect_1.Rect(childRect.getRight() - 2, childY, 3, childHeight);
                        dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, this._children.length, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                    }
                }
                else {
                    const outlineRect = new Rect_1.Rect(this._tabHeaderRect.x + 1, this._tabHeaderRect.y + 2, 3, 18);
                    dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, 0, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                }
            }
            else {
                if (this._children.length > 0) {
                    let child = this._children[0];
                    let childRect = child.getTabRect();
                    const childX = childRect.x;
                    const childWidth = childRect.width;
                    let pos = this._tabHeaderRect.y;
                    let childCenter = 0;
                    for (let i = 0; i < this._children.length; i++) {
                        child = this._children[i];
                        childRect = child.getTabRect();
                        childCenter = childRect.y + childRect.height / 2;
                        if (y >= pos && y < childCenter) {
                            const outlineRect = new Rect_1.Rect(childX, childRect.y - 2, childWidth, 3);
                            dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, i, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                            break;
                        }
                        pos = childCenter;
                    }
                    if (dropInfo == null) {
                        const outlineRect = new Rect_1.Rect(childX, childRect.getBottom() - 2, childWidth, 3);
                        dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, this._children.length, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                    }
                }
                else {
                    const outlineRect = new Rect_1.Rect(this._tabHeaderRect.x + 2, this._tabHeaderRect.y + 1, 18, 3);
                    dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, 0, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                }
            }
            if (!dragNode._canDockInto(dragNode, dropInfo)) {
                return undefined;
            }
        }
        else if (this.getSelected() !== -1 && this._contentRect.contains(x, y)) {
            const outlineRect = this._contentRect;
            dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
            if (!dragNode._canDockInto(dragNode, dropInfo)) {
                return undefined;
            }
        }
        return dropInfo;
    }
    /** @internal */
    drop(dragNode, location, index, select) {
        let fromIndex = 0;
        const dragParent = dragNode.getParent();
        if (dragParent !== undefined) {
            fromIndex = dragParent._removeChild(dragNode);
            // if selected node in border is being docked into a different border then deselect border tabs
            if (dragParent !== this && dragParent instanceof BorderNode && dragParent.getSelected() === fromIndex) {
                dragParent._setSelected(-1);
            }
            else {
                (0, Utils_1.adjustSelectedIndex)(dragParent, fromIndex);
            }
        }
        // if dropping a tab back to same tabset and moving to forward position then reduce insertion index
        if (dragNode.getType() === TabNode_1.TabNode.TYPE && dragParent === this && fromIndex < index && index > 0) {
            index--;
        }
        // simple_bundled dock to existing tabset
        let insertPos = index;
        if (insertPos === -1) {
            insertPos = this._children.length;
        }
        if (dragNode.getType() === TabNode_1.TabNode.TYPE) {
            this._addChild(dragNode, insertPos);
        }
        if (select || (select !== false && this.isAutoSelectTab())) {
            this._setSelected(insertPos);
        }
        this._model._tidy();
    }
    toJson() {
        const json = {};
        BorderNode._attributeDefinitions.toJson(json, this._attributes);
        json.location = this._location.getName();
        json.children = this._children.map((child) => child.toJson());
        return json;
    }
    /** @internal */
    _getSplitterBounds(splitter, useMinSize = false) {
        const pBounds = [0, 0];
        const minSize = useMinSize ? this.getMinSize() : 0;
        const outerRect = this._model._getOuterInnerRects().outer;
        const innerRect = this._model._getOuterInnerRects().inner;
        const rootRow = this._model.getRoot();
        if (this._location === DockLocation_1.DockLocation.TOP) {
            pBounds[0] = outerRect.y + minSize;
            pBounds[1] = Math.max(pBounds[0], innerRect.getBottom() - splitter.getHeight() - rootRow.getMinHeight());
        }
        else if (this._location === DockLocation_1.DockLocation.LEFT) {
            pBounds[0] = outerRect.x + minSize;
            pBounds[1] = Math.max(pBounds[0], innerRect.getRight() - splitter.getWidth() - rootRow.getMinWidth());
        }
        else if (this._location === DockLocation_1.DockLocation.BOTTOM) {
            pBounds[1] = outerRect.getBottom() - splitter.getHeight() - minSize;
            pBounds[0] = Math.min(pBounds[1], innerRect.y + rootRow.getMinHeight());
        }
        else if (this._location === DockLocation_1.DockLocation.RIGHT) {
            pBounds[1] = outerRect.getRight() - splitter.getWidth() - minSize;
            pBounds[0] = Math.min(pBounds[1], innerRect.x + rootRow.getMinWidth());
        }
        return pBounds;
    }
    /** @internal */
    _calculateSplit(splitter, splitterPos) {
        const pBounds = this._getSplitterBounds(splitter);
        if (this._location === DockLocation_1.DockLocation.BOTTOM || this._location === DockLocation_1.DockLocation.RIGHT) {
            return Math.max(0, pBounds[1] - splitterPos);
        }
        else {
            return Math.max(0, splitterPos - pBounds[0]);
        }
    }
    /** @internal */
    _getAttributeDefinitions() {
        return BorderNode._attributeDefinitions;
    }
    /** @internal */
    static getAttributeDefinitions() {
        return BorderNode._attributeDefinitions;
    }
}
exports.BorderNode = BorderNode;
BorderNode.TYPE = "border";
/** @internal */
BorderNode._attributeDefinitions = BorderNode._createAttributeDefinitions();
//# sourceMappingURL=BorderNode.js.map

/***/ }),

/***/ 1648:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Orientation = void 0;
class Orientation {
    static flip(from) {
        if (from === Orientation.HORZ) {
            return Orientation.VERT;
        }
        else {
            return Orientation.HORZ;
        }
    }
    /** @internal */
    constructor(name) {
        this._name = name;
    }
    getName() {
        return this._name;
    }
    toString() {
        return this._name;
    }
}
exports.Orientation = Orientation;
Orientation.HORZ = new Orientation("horz");
Orientation.VERT = new Orientation("vert");
//# sourceMappingURL=Orientation.js.map

/***/ }),

/***/ 1809:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TabSet = void 0;
const React = __webpack_require__(6540);
const I18nLabel_1 = __webpack_require__(300);
const Actions_1 = __webpack_require__(9103);
const PopupMenu_1 = __webpack_require__(9919);
const TabButton_1 = __webpack_require__(5641);
const TabOverflowHook_1 = __webpack_require__(2272);
const Orientation_1 = __webpack_require__(1648);
const Types_1 = __webpack_require__(6643);
const Utils_1 = __webpack_require__(343);
/** @internal */
const TabSet = (props) => {
    const { node, layout, iconFactory, titleFactory, icons, path } = props;
    const toolbarRef = React.useRef(null);
    const overflowbuttonRef = React.useRef(null);
    const tabbarInnerRef = React.useRef(null);
    const stickyButtonsRef = React.useRef(null);
    const { selfRef, position, userControlledLeft, hiddenTabs, onMouseWheel, tabsTruncated } = (0, TabOverflowHook_1.useTabOverflow)(node, Orientation_1.Orientation.HORZ, toolbarRef, stickyButtonsRef);
    const onOverflowClick = (event) => {
        const callback = layout.getShowOverflowMenu();
        if (callback !== undefined) {
            callback(node, event, hiddenTabs, onOverflowItemSelect);
        }
        else {
            const element = overflowbuttonRef.current;
            (0, PopupMenu_1.showPopup)(element, hiddenTabs, onOverflowItemSelect, layout, iconFactory, titleFactory);
        }
        event.stopPropagation();
    };
    const onOverflowItemSelect = (item) => {
        layout.doAction(Actions_1.Actions.selectTab(item.node.getId()));
        userControlledLeft.current = false;
    };
    const onMouseDown = (event) => {
        if (!(0, Utils_1.isAuxMouseEvent)(event)) {
            let name = node.getName();
            if (name === undefined) {
                name = "";
            }
            else {
                name = ": " + name;
            }
            layout.doAction(Actions_1.Actions.setActiveTabset(node.getId()));
            if (!layout.getEditingTab()) {
                const message = layout.i18nName(I18nLabel_1.I18nLabel.Move_Tabset, name);
                if (node.getModel().getMaximizedTabset() !== undefined) {
                    layout.dragStart(event, message, node, false, (event2) => undefined, onDoubleClick);
                }
                else {
                    layout.dragStart(event, message, node, node.isEnableDrag(), (event2) => undefined, onDoubleClick);
                }
            }
        }
    };
    const onAuxMouseClick = (event) => {
        if ((0, Utils_1.isAuxMouseEvent)(event)) {
            layout.auxMouseClick(node, event);
        }
    };
    const onContextMenu = (event) => {
        layout.showContextMenu(node, event);
    };
    const onInterceptMouseDown = (event) => {
        event.stopPropagation();
    };
    const onMaximizeToggle = (event) => {
        if (node.canMaximize()) {
            layout.maximize(node);
        }
        event.stopPropagation();
    };
    const onClose = (event) => {
        layout.doAction(Actions_1.Actions.deleteTabset(node.getId()));
        event.stopPropagation();
    };
    const onCloseTab = (event) => {
        layout.doAction(Actions_1.Actions.deleteTab(node.getChildren()[0].getId()));
        event.stopPropagation();
    };
    const onFloatTab = (event) => {
        if (selectedTabNode !== undefined) {
            layout.doAction(Actions_1.Actions.floatTab(selectedTabNode.getId()));
        }
        event.stopPropagation();
    };
    const onDoubleClick = (event) => {
        if (node.canMaximize()) {
            layout.maximize(node);
        }
    };
    // Start Render
    const cm = layout.getClassName;
    // tabbar inner can get shifted left via tab rename, this resets scrollleft to 0
    if (tabbarInnerRef.current !== null && tabbarInnerRef.current.scrollLeft !== 0) {
        tabbarInnerRef.current.scrollLeft = 0;
    }
    const selectedTabNode = node.getSelectedNode();
    let style = node._styleWithPosition();
    if (node.getModel().getMaximizedTabset() !== undefined && !node.isMaximized()) {
        (0, Utils_1.hideElement)(style, node.getModel().isUseVisibility());
    }
    const tabs = [];
    if (node.isEnableTabStrip()) {
        for (let i = 0; i < node.getChildren().length; i++) {
            const child = node.getChildren()[i];
            let isSelected = node.getSelected() === i;
            tabs.push(React.createElement(TabButton_1.TabButton, { layout: layout, node: child, path: path + "/tb" + i, key: child.getId(), selected: isSelected, iconFactory: iconFactory, titleFactory: titleFactory, icons: icons }));
            if (i < node.getChildren().length - 1) {
                tabs.push(React.createElement("div", { key: "divider" + i, className: cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_TAB_DIVIDER) }));
            }
        }
    }
    const showHeader = node.getName() !== undefined;
    let stickyButtons = [];
    let buttons = [];
    let headerButtons = [];
    // allow customization of header contents and buttons
    const renderState = { headerContent: node.getName(), stickyButtons, buttons, headerButtons, overflowPosition: undefined };
    layout.customizeTabSet(node, renderState);
    const headerContent = renderState.headerContent;
    stickyButtons = renderState.stickyButtons;
    buttons = renderState.buttons;
    headerButtons = renderState.headerButtons;
    const isTabStretch = node.isEnableSingleTabStretch() && node.getChildren().length === 1;
    const showClose = (isTabStretch && (node.getChildren()[0].isEnableClose())) || node.isEnableClose();
    if (renderState.overflowPosition === undefined) {
        renderState.overflowPosition = stickyButtons.length;
    }
    if (stickyButtons.length > 0) {
        if (tabsTruncated || isTabStretch) {
            buttons = [...stickyButtons, ...buttons];
        }
        else {
            tabs.push(React.createElement("div", { ref: stickyButtonsRef, key: "sticky_buttons_container", onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown, onDragStart: (e) => { e.preventDefault(); }, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER) }, stickyButtons));
        }
    }
    if (hiddenTabs.length > 0) {
        const overflowTitle = layout.i18nName(I18nLabel_1.I18nLabel.Overflow_Menu_Tooltip);
        let overflowContent;
        if (typeof icons.more === "function") {
            overflowContent = icons.more(node, hiddenTabs);
        }
        else {
            overflowContent = (React.createElement(React.Fragment, null,
                icons.more,
                React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT) }, hiddenTabs.length)));
        }
        buttons.splice(Math.min(renderState.overflowPosition, buttons.length), 0, React.createElement("button", { key: "overflowbutton", "data-layout-path": path + "/button/overflow", ref: overflowbuttonRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW), title: overflowTitle, onClick: onOverflowClick, onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown }, overflowContent));
    }
    if (selectedTabNode !== undefined && layout.isSupportsPopout() && selectedTabNode.isEnableFloat() && !selectedTabNode.isFloating()) {
        const floatTitle = layout.i18nName(I18nLabel_1.I18nLabel.Float_Tab);
        buttons.push(React.createElement("button", { key: "float", "data-layout-path": path + "/button/float", title: floatTitle, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_FLOAT), onClick: onFloatTab, onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown }, (typeof icons.popout === "function") ? icons.popout(selectedTabNode) : icons.popout));
    }
    if (node.canMaximize()) {
        const minTitle = layout.i18nName(I18nLabel_1.I18nLabel.Restore);
        const maxTitle = layout.i18nName(I18nLabel_1.I18nLabel.Maximize);
        const btns = showHeader ? headerButtons : buttons;
        btns.push(React.createElement("button", { key: "max", "data-layout-path": path + "/button/max", title: node.isMaximized() ? minTitle : maxTitle, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_ + (node.isMaximized() ? "max" : "min")), onClick: onMaximizeToggle, onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown }, node.isMaximized() ?
            (typeof icons.restore === "function") ? icons.restore(node) : icons.restore :
            (typeof icons.maximize === "function") ? icons.maximize(node) : icons.maximize));
    }
    if (!node.isMaximized() && showClose) {
        const title = isTabStretch ? layout.i18nName(I18nLabel_1.I18nLabel.Close_Tab) : layout.i18nName(I18nLabel_1.I18nLabel.Close_Tabset);
        const btns = showHeader ? headerButtons : buttons;
        btns.push(React.createElement("button", { key: "close", "data-layout-path": path + "/button/close", title: title, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_CLOSE), onClick: isTabStretch ? onCloseTab : onClose, onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown }, (typeof icons.closeTabset === "function") ? icons.closeTabset(node) : icons.closeTabset));
    }
    const toolbar = (React.createElement("div", { key: "toolbar", ref: toolbarRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR), onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown, onDragStart: (e) => { e.preventDefault(); } }, buttons));
    let header;
    let tabStrip;
    let tabStripClasses = cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_TABBAR_OUTER);
    if (node.getClassNameTabStrip() !== undefined) {
        tabStripClasses += " " + node.getClassNameTabStrip();
    }
    tabStripClasses += " " + Types_1.CLASSES.FLEXLAYOUT__TABSET_TABBAR_OUTER_ + node.getTabLocation();
    if (node.isActive() && !showHeader) {
        tabStripClasses += " " + cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_SELECTED);
    }
    if (node.isMaximized() && !showHeader) {
        tabStripClasses += " " + cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_MAXIMIZED);
    }
    if (isTabStretch) {
        const tabNode = node.getChildren()[0];
        if (tabNode.getTabSetClassName() !== undefined) {
            tabStripClasses += " " + tabNode.getTabSetClassName();
        }
    }
    if (showHeader) {
        const headerToolbar = (React.createElement("div", { key: "toolbar", ref: toolbarRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR), onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown, onDragStart: (e) => { e.preventDefault(); } }, headerButtons));
        let tabHeaderClasses = cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_HEADER);
        if (node.isActive()) {
            tabHeaderClasses += " " + cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_SELECTED);
        }
        if (node.isMaximized()) {
            tabHeaderClasses += " " + cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_MAXIMIZED);
        }
        if (node.getClassNameHeader() !== undefined) {
            tabHeaderClasses += " " + node.getClassNameHeader();
        }
        header = (React.createElement("div", { className: tabHeaderClasses, style: { height: node.getHeaderHeight() + "px" }, "data-layout-path": path + "/header", onMouseDown: onMouseDown, onContextMenu: onContextMenu, onClick: onAuxMouseClick, onAuxClick: onAuxMouseClick, onTouchStart: onMouseDown },
            React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_HEADER_CONTENT) }, headerContent),
            headerToolbar));
    }
    const tabStripStyle = { height: node.getTabStripHeight() + "px" };
    tabStrip = (React.createElement("div", { className: tabStripClasses, style: tabStripStyle, "data-layout-path": path + "/tabstrip", onMouseDown: onMouseDown, onContextMenu: onContextMenu, onClick: onAuxMouseClick, onAuxClick: onAuxMouseClick, onTouchStart: onMouseDown },
        React.createElement("div", { ref: tabbarInnerRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_ + node.getTabLocation()) },
            React.createElement("div", { style: { left: position, width: (isTabStretch ? "100%" : "10000px") }, className: cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER_ + node.getTabLocation()) }, tabs)),
        toolbar));
    style = layout.styleFont(style);
    var placeHolder = undefined;
    if (node.getChildren().length === 0) {
        const placeHolderCallback = layout.getTabSetPlaceHolderCallback();
        if (placeHolderCallback) {
            placeHolder = placeHolderCallback(node);
        }
    }
    const center = React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TABSET_CONTENT) }, placeHolder);
    var content;
    if (node.getTabLocation() === "top") {
        content = React.createElement(React.Fragment, null,
            header,
            tabStrip,
            center);
    }
    else {
        content = React.createElement(React.Fragment, null,
            header,
            center,
            tabStrip);
    }
    return (React.createElement("div", { ref: selfRef, dir: "ltr", "data-layout-path": path, style: style, className: cm(Types_1.CLASSES.FLEXLAYOUT__TABSET), onWheel: onMouseWheel }, content));
};
exports.TabSet = TabSet;
//# sourceMappingURL=TabSet.js.map

/***/ }),

/***/ 2162:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";
/**
 * @license React
 * use-sync-external-store-shim/with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */


var React = __webpack_require__(6540),
  shim = __webpack_require__(9888);
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
  useSyncExternalStore = shim.useSyncExternalStore,
  useRef = React.useRef,
  useEffect = React.useEffect,
  useMemo = React.useMemo,
  useDebugValue = React.useDebugValue;
exports.useSyncExternalStoreWithSelector = function (
  subscribe,
  getSnapshot,
  getServerSnapshot,
  selector,
  isEqual
) {
  var instRef = useRef(null);
  if (null === instRef.current) {
    var inst = { hasValue: !1, value: null };
    instRef.current = inst;
  } else inst = instRef.current;
  instRef = useMemo(
    function () {
      function memoizedSelector(nextSnapshot) {
        if (!hasMemo) {
          hasMemo = !0;
          memoizedSnapshot = nextSnapshot;
          nextSnapshot = selector(nextSnapshot);
          if (void 0 !== isEqual && inst.hasValue) {
            var currentSelection = inst.value;
            if (isEqual(currentSelection, nextSnapshot))
              return (memoizedSelection = currentSelection);
          }
          return (memoizedSelection = nextSnapshot);
        }
        currentSelection = memoizedSelection;
        if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
        var nextSelection = selector(nextSnapshot);
        if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
          return (memoizedSnapshot = nextSnapshot), currentSelection;
        memoizedSnapshot = nextSnapshot;
        return (memoizedSelection = nextSelection);
      }
      var hasMemo = !1,
        memoizedSnapshot,
        memoizedSelection,
        maybeGetServerSnapshot =
          void 0 === getServerSnapshot ? null : getServerSnapshot;
      return [
        function () {
          return memoizedSelector(getSnapshot());
        },
        null === maybeGetServerSnapshot
          ? void 0
          : function () {
              return memoizedSelector(maybeGetServerSnapshot());
            }
      ];
    },
    [getSnapshot, getServerSnapshot, selector, isEqual]
  );
  var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
  useEffect(
    function () {
      inst.hasValue = !0;
      inst.value = value;
    },
    [value]
  );
  useDebugValue(value);
  return value;
};


/***/ }),

/***/ 2272:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.useTabOverflow = void 0;
const React = __webpack_require__(6540);
const Rect_1 = __webpack_require__(2530);
const TabSetNode_1 = __webpack_require__(9555);
const Orientation_1 = __webpack_require__(1648);
/** @internal */
const useTabOverflow = (node, orientation, toolbarRef, stickyButtonsRef) => {
    const firstRender = React.useRef(true);
    const tabsTruncated = React.useRef(false);
    const lastRect = React.useRef(new Rect_1.Rect(0, 0, 0, 0));
    const selfRef = React.useRef(null);
    const [position, setPosition] = React.useState(0);
    const userControlledLeft = React.useRef(false);
    const [hiddenTabs, setHiddenTabs] = React.useState([]);
    const lastHiddenCount = React.useRef(0);
    // if selected node or tabset/border rectangle change then unset usercontrolled (so selected tab will be kept in view)
    React.useLayoutEffect(() => {
        userControlledLeft.current = false;
    }, [node.getSelectedNode(), node.getRect().width, node.getRect().height]);
    React.useLayoutEffect(() => {
        updateVisibleTabs();
    });
    const instance = selfRef.current;
    React.useEffect(() => {
        if (!instance) {
            return;
        }
        instance.addEventListener("wheel", onWheel, { passive: false });
        return () => {
            instance.removeEventListener("wheel", onWheel);
        };
    }, [instance]);
    // needed to prevent default mouse wheel over tabset/border (cannot do with react event?)
    const onWheel = (event) => {
        event.preventDefault();
    };
    const getNear = (rect) => {
        if (orientation === Orientation_1.Orientation.HORZ) {
            return rect.x;
        }
        else {
            return rect.y;
        }
    };
    const getFar = (rect) => {
        if (orientation === Orientation_1.Orientation.HORZ) {
            return rect.getRight();
        }
        else {
            return rect.getBottom();
        }
    };
    const getSize = (rect) => {
        if (orientation === Orientation_1.Orientation.HORZ) {
            return rect.width;
        }
        else {
            return rect.height;
        }
    };
    const updateVisibleTabs = () => {
        const tabMargin = 2;
        if (firstRender.current === true) {
            tabsTruncated.current = false;
        }
        const nodeRect = node instanceof TabSetNode_1.TabSetNode ? node.getRect() : node.getTabHeaderRect();
        let lastChild = node.getChildren()[node.getChildren().length - 1];
        const stickyButtonsSize = stickyButtonsRef.current === null ? 0 : getSize(stickyButtonsRef.current.getBoundingClientRect());
        if (firstRender.current === true ||
            (lastHiddenCount.current === 0 && hiddenTabs.length !== 0) ||
            nodeRect.width !== lastRect.current.width || // incase rect changed between first render and second
            nodeRect.height !== lastRect.current.height) {
            lastHiddenCount.current = hiddenTabs.length;
            lastRect.current = nodeRect;
            const enabled = node instanceof TabSetNode_1.TabSetNode ? node.isEnableTabStrip() === true : true;
            let endPos = getFar(nodeRect) - stickyButtonsSize;
            if (toolbarRef.current !== null) {
                endPos -= getSize(toolbarRef.current.getBoundingClientRect());
            }
            if (enabled && node.getChildren().length > 0) {
                if (hiddenTabs.length === 0 && position === 0 && getFar(lastChild.getTabRect()) + tabMargin < endPos) {
                    return; // nothing to do all tabs are shown in available space
                }
                let shiftPos = 0;
                const selectedTab = node.getSelectedNode();
                if (selectedTab && !userControlledLeft.current) {
                    const selectedRect = selectedTab.getTabRect();
                    const selectedStart = getNear(selectedRect) - tabMargin;
                    const selectedEnd = getFar(selectedRect) + tabMargin;
                    // when selected tab is larger than available space then align left
                    if (getSize(selectedRect) + 2 * tabMargin >= endPos - getNear(nodeRect)) {
                        shiftPos = getNear(nodeRect) - selectedStart;
                    }
                    else {
                        if (selectedEnd > endPos || selectedStart < getNear(nodeRect)) {
                            if (selectedStart < getNear(nodeRect)) {
                                shiftPos = getNear(nodeRect) - selectedStart;
                            }
                            // use second if statement to prevent tab moving back then forwards if not enough space for single tab
                            if (selectedEnd + shiftPos > endPos) {
                                shiftPos = endPos - selectedEnd;
                            }
                        }
                    }
                }
                const extraSpace = Math.max(0, endPos - (getFar(lastChild.getTabRect()) + tabMargin + shiftPos));
                const newPosition = Math.min(0, position + shiftPos + extraSpace);
                // find hidden tabs
                const diff = newPosition - position;
                const hidden = [];
                for (let i = 0; i < node.getChildren().length; i++) {
                    const child = node.getChildren()[i];
                    if (getNear(child.getTabRect()) + diff < getNear(nodeRect) || getFar(child.getTabRect()) + diff > endPos) {
                        hidden.push({ node: child, index: i });
                    }
                }
                if (hidden.length > 0) {
                    tabsTruncated.current = true;
                }
                firstRender.current = false; // need to do a second render
                setHiddenTabs(hidden);
                setPosition(newPosition);
            }
        }
        else {
            firstRender.current = true;
        }
    };
    const onMouseWheel = (event) => {
        let delta = 0;
        if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
            delta = -event.deltaX;
        }
        else {
            delta = -event.deltaY;
        }
        if (event.deltaMode === 1) {
            // DOM_DELTA_LINE	0x01	The delta values are specified in lines.
            delta *= 40;
        }
        setPosition(position + delta);
        userControlledLeft.current = true;
        event.stopPropagation();
    };
    return { selfRef, position, userControlledLeft, hiddenTabs, onMouseWheel, tabsTruncated: tabsTruncated.current };
};
exports.useTabOverflow = useTabOverflow;
//# sourceMappingURL=TabOverflowHook.js.map

/***/ }),

/***/ 2429:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.randomUUID = exports.adjustSelectedIndex = exports.adjustSelectedIndexAfterDock = exports.adjustSelectedIndexAfterFloat = void 0;
const TabSetNode_1 = __webpack_require__(9555);
const BorderNode_1 = __webpack_require__(1480);
/** @internal */
function adjustSelectedIndexAfterFloat(node) {
    const parent = node.getParent();
    if (parent !== null) {
        if (parent instanceof TabSetNode_1.TabSetNode) {
            let found = false;
            let newSelected = 0;
            const children = parent.getChildren();
            for (let i = 0; i < children.length; i++) {
                const child = children[i];
                if (child === node) {
                    found = true;
                }
                else {
                    if (!child.isFloating()) {
                        newSelected = i;
                        if (found)
                            break;
                    }
                }
            }
            parent._setSelected(newSelected);
        }
        else if (parent instanceof BorderNode_1.BorderNode) {
            parent._setSelected(-1);
        }
    }
}
exports.adjustSelectedIndexAfterFloat = adjustSelectedIndexAfterFloat;
/** @internal */
function adjustSelectedIndexAfterDock(node) {
    const parent = node.getParent();
    if (parent !== null && (parent instanceof TabSetNode_1.TabSetNode || parent instanceof BorderNode_1.BorderNode)) {
        const children = parent.getChildren();
        for (let i = 0; i < children.length; i++) {
            const child = children[i];
            if (child === node) {
                parent._setSelected(i);
                return;
            }
        }
    }
}
exports.adjustSelectedIndexAfterDock = adjustSelectedIndexAfterDock;
/** @internal */
function adjustSelectedIndex(parent, removedIndex) {
    // for the tabset/border being removed from set the selected index
    if (parent !== undefined && (parent.getType() === TabSetNode_1.TabSetNode.TYPE || parent.getType() === BorderNode_1.BorderNode.TYPE)) {
        const selectedIndex = parent.getSelected();
        if (selectedIndex !== -1) {
            if (removedIndex === selectedIndex && parent.getChildren().length > 0) {
                if (removedIndex >= parent.getChildren().length) {
                    // removed last tab; select new last tab
                    parent._setSelected(parent.getChildren().length - 1);
                }
                else {
                    // leave selected index as is, selecting next tab after this one
                }
            }
            else if (removedIndex < selectedIndex) {
                parent._setSelected(selectedIndex - 1);
            }
            else if (removedIndex > selectedIndex) {
                // leave selected index as is
            }
            else {
                parent._setSelected(-1);
            }
        }
    }
}
exports.adjustSelectedIndex = adjustSelectedIndex;
function randomUUID() {
    // @ts-ignore
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
}
exports.randomUUID = randomUUID;
//# sourceMappingURL=Utils.js.map

/***/ }),

/***/ 2439:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Splitter = void 0;
const React = __webpack_require__(6540);
const DragDrop_1 = __webpack_require__(883);
const Actions_1 = __webpack_require__(9103);
const BorderNode_1 = __webpack_require__(1480);
const Orientation_1 = __webpack_require__(1648);
const Types_1 = __webpack_require__(6643);
/** @internal */
const Splitter = (props) => {
    const { layout, node, path } = props;
    const pBounds = React.useRef([]);
    const outlineDiv = React.useRef(undefined);
    const parentNode = node.getParent();
    const onMouseDown = (event) => {
        var _a;
        DragDrop_1.DragDrop.instance.setGlassCursorOverride(node.getOrientation() === Orientation_1.Orientation.HORZ
            ? "ns-resize"
            : "ew-resize");
        DragDrop_1.DragDrop.instance.startDrag(event, onDragStart, onDragMove, onDragEnd, onDragCancel, undefined, undefined, layout.getCurrentDocument(), (_a = layout.getRootDiv()) !== null && _a !== void 0 ? _a : undefined);
        pBounds.current = parentNode._getSplitterBounds(node, true);
        const rootdiv = layout.getRootDiv();
        outlineDiv.current = layout.getCurrentDocument().createElement("div");
        outlineDiv.current.style.position = "absolute";
        outlineDiv.current.className = layout.getClassName(Types_1.CLASSES.FLEXLAYOUT__SPLITTER_DRAG);
        outlineDiv.current.style.cursor = node.getOrientation() === Orientation_1.Orientation.HORZ ? "ns-resize" : "ew-resize";
        const r = node.getRect();
        if (node.getOrientation() === Orientation_1.Orientation.VERT && r.width < 2) {
            r.width = 2;
        }
        else if (node.getOrientation() === Orientation_1.Orientation.HORZ && r.height < 2) {
            r.height = 2;
        }
        r.positionElement(outlineDiv.current);
        if (rootdiv) {
            rootdiv.appendChild(outlineDiv.current);
        }
    };
    const onDragCancel = (_wasDragging) => {
        const rootdiv = layout.getRootDiv();
        if (rootdiv) {
            rootdiv.removeChild(outlineDiv.current);
        }
    };
    const onDragStart = () => {
        return true;
    };
    const onDragMove = (event) => {
        const clientRect = layout.getDomRect();
        if (!clientRect) {
            return;
        }
        const pos = {
            x: event.clientX - clientRect.left,
            y: event.clientY - clientRect.top,
        };
        if (outlineDiv) {
            if (node.getOrientation() === Orientation_1.Orientation.HORZ) {
                outlineDiv.current.style.top = getBoundPosition(pos.y - 4) + "px";
            }
            else {
                outlineDiv.current.style.left = getBoundPosition(pos.x - 4) + "px";
            }
        }
        if (layout.isRealtimeResize()) {
            updateLayout();
        }
    };
    const updateLayout = () => {
        let value = 0;
        if (outlineDiv) {
            if (node.getOrientation() === Orientation_1.Orientation.HORZ) {
                value = outlineDiv.current.offsetTop;
            }
            else {
                value = outlineDiv.current.offsetLeft;
            }
        }
        if (parentNode instanceof BorderNode_1.BorderNode) {
            const pos = parentNode._calculateSplit(node, value);
            layout.doAction(Actions_1.Actions.adjustBorderSplit(node.getParent().getId(), pos));
        }
        else {
            const splitSpec = parentNode._calculateSplit(node, value);
            if (splitSpec !== undefined) {
                layout.doAction(Actions_1.Actions.adjustSplit(splitSpec));
            }
        }
    };
    const onDragEnd = () => {
        updateLayout();
        const rootdiv = layout.getRootDiv();
        if (rootdiv) {
            rootdiv.removeChild(outlineDiv.current);
        }
    };
    const getBoundPosition = (p) => {
        const bounds = pBounds.current;
        let rtn = p;
        if (p < bounds[0]) {
            rtn = bounds[0];
        }
        if (p > bounds[1]) {
            rtn = bounds[1];
        }
        return rtn;
    };
    const cm = layout.getClassName;
    let r = node.getRect();
    const style = r.styleWithPosition({
        cursor: node.getOrientation() === Orientation_1.Orientation.HORZ ? "ns-resize" : "ew-resize",
    });
    let className = cm(Types_1.CLASSES.FLEXLAYOUT__SPLITTER) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__SPLITTER_ + node.getOrientation().getName());
    if (parentNode instanceof BorderNode_1.BorderNode) {
        className += " " + cm(Types_1.CLASSES.FLEXLAYOUT__SPLITTER_BORDER);
    }
    else {
        if (node.getModel().getMaximizedTabset() !== undefined) {
            style.display = "none";
        }
    }
    const extra = node.getModel().getSplitterExtra();
    if (extra === 0) {
        return (React.createElement("div", { style: style, "data-layout-path": path, className: className, onTouchStart: onMouseDown, onMouseDown: onMouseDown }));
    }
    else {
        // add extended transparent div for hit testing
        // extends forward only, so as not to interfere with scrollbars
        let r2 = r.clone();
        r2.x = 0;
        r2.y = 0;
        if (node.getOrientation() === Orientation_1.Orientation.VERT) {
            r2.width += extra;
        }
        else {
            r2.height += extra;
        }
        const style2 = r2.styleWithPosition({
            cursor: node.getOrientation() === Orientation_1.Orientation.HORZ ? "ns-resize" : "ew-resize"
        });
        const className2 = cm(Types_1.CLASSES.FLEXLAYOUT__SPLITTER_EXTRA);
        return (React.createElement("div", { style: style, "data-layout-path": path, className: className },
            React.createElement("div", { style: style2, className: className2, onTouchStart: onMouseDown, onMouseDown: onMouseDown })));
    }
};
exports.Splitter = Splitter;
//# sourceMappingURL=Splitter.js.map

/***/ }),

/***/ 2486:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TabButtonStamp = void 0;
const React = __webpack_require__(6540);
const Types_1 = __webpack_require__(6643);
const Utils_1 = __webpack_require__(343);
/** @internal */
const TabButtonStamp = (props) => {
    const { layout, node, iconFactory, titleFactory } = props;
    const selfRef = React.useRef(null);
    const cm = layout.getClassName;
    let classNames = cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_STAMP);
    const renderState = (0, Utils_1.getRenderStateEx)(layout, node, iconFactory, titleFactory);
    let content = renderState.content ? (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_CONTENT) }, renderState.content))
        : node._getNameForOverflowMenu();
    const leading = renderState.leading ? (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING) }, renderState.leading)) : null;
    return (React.createElement("div", { ref: selfRef, className: classNames, title: node.getHelpText() },
        leading,
        content));
};
exports.TabButtonStamp = TabButtonStamp;
//# sourceMappingURL=TabButtonStamp.js.map

/***/ }),

/***/ 2530:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Rect = void 0;
const Orientation_1 = __webpack_require__(1648);
class Rect {
    static empty() {
        return new Rect(0, 0, 0, 0);
    }
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    static fromElement(element) {
        let { x, y, width, height } = element.getBoundingClientRect();
        return new Rect(x, y, width, height);
    }
    clone() {
        return new Rect(this.x, this.y, this.width, this.height);
    }
    equals(rect) {
        return this.x === (rect === null || rect === void 0 ? void 0 : rect.x) && this.y === (rect === null || rect === void 0 ? void 0 : rect.y) && this.width === (rect === null || rect === void 0 ? void 0 : rect.width) && this.height === (rect === null || rect === void 0 ? void 0 : rect.height);
    }
    getBottom() {
        return this.y + this.height;
    }
    getRight() {
        return this.x + this.width;
    }
    getCenter() {
        return { x: this.x + this.width / 2, y: this.y + this.height / 2 };
    }
    positionElement(element, position) {
        this.styleWithPosition(element.style, position);
    }
    styleWithPosition(style, position = "absolute") {
        style.left = this.x + "px";
        style.top = this.y + "px";
        style.width = Math.max(0, this.width) + "px"; // need Math.max to prevent -ve, cause error in IE
        style.height = Math.max(0, this.height) + "px";
        style.position = position;
        return style;
    }
    contains(x, y) {
        if (this.x <= x && x <= this.getRight() && this.y <= y && y <= this.getBottom()) {
            return true;
        }
        else {
            return false;
        }
    }
    removeInsets(insets) {
        return new Rect(this.x + insets.left, this.y + insets.top, Math.max(0, this.width - insets.left - insets.right), Math.max(0, this.height - insets.top - insets.bottom));
    }
    centerInRect(outerRect) {
        this.x = (outerRect.width - this.width) / 2;
        this.y = (outerRect.height - this.height) / 2;
    }
    /** @internal */
    _getSize(orientation) {
        let prefSize = this.width;
        if (orientation === Orientation_1.Orientation.VERT) {
            prefSize = this.height;
        }
        return prefSize;
    }
    toString() {
        return "(Rect: x=" + this.x + ", y=" + this.y + ", width=" + this.width + ", height=" + this.height + ")";
    }
}
exports.Rect = Rect;
//# sourceMappingURL=Rect.js.map

/***/ }),

/***/ 3072:
/***/ (function(__unused_webpack_module, exports) {

"use strict";
/** @license React v16.13.1
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;
exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};
exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;


/***/ }),

/***/ 3174:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  J: function() { return /* binding */ serializeStyles; }
});

;// ./node_modules/@emotion/hash/dist/emotion-hash.esm.js
/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
  // 'm' and 'r' are mixing constants generated offline.
  // They're not really 'magic', they just happen to work well.
  // const m = 0x5bd1e995;
  // const r = 24;
  // Initialize the hash
  var h = 0; // Mix 4 bytes at a time into the hash

  var k,
      i = 0,
      len = str.length;

  for (; len >= 4; ++i, len -= 4) {
    k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
    k =
    /* Math.imul(k, m): */
    (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
    k ^=
    /* k >>> r: */
    k >>> 24;
    h =
    /* Math.imul(k, m): */
    (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
    /* Math.imul(h, m): */
    (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
  } // Handle the last few bytes of the input array


  switch (len) {
    case 3:
      h ^= (str.charCodeAt(i + 2) & 0xff) << 16;

    case 2:
      h ^= (str.charCodeAt(i + 1) & 0xff) << 8;

    case 1:
      h ^= str.charCodeAt(i) & 0xff;
      h =
      /* Math.imul(h, m): */
      (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
  } // Do a few final mixes of the hash to ensure the last few
  // bytes are well-incorporated.


  h ^= h >>> 13;
  h =
  /* Math.imul(h, m): */
  (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
  return ((h ^ h >>> 15) >>> 0).toString(36);
}



;// ./node_modules/@emotion/unitless/dist/emotion-unitless.esm.js
var unitlessKeys = {
  animationIterationCount: 1,
  aspectRatio: 1,
  borderImageOutset: 1,
  borderImageSlice: 1,
  borderImageWidth: 1,
  boxFlex: 1,
  boxFlexGroup: 1,
  boxOrdinalGroup: 1,
  columnCount: 1,
  columns: 1,
  flex: 1,
  flexGrow: 1,
  flexPositive: 1,
  flexShrink: 1,
  flexNegative: 1,
  flexOrder: 1,
  gridRow: 1,
  gridRowEnd: 1,
  gridRowSpan: 1,
  gridRowStart: 1,
  gridColumn: 1,
  gridColumnEnd: 1,
  gridColumnSpan: 1,
  gridColumnStart: 1,
  msGridRow: 1,
  msGridRowSpan: 1,
  msGridColumn: 1,
  msGridColumnSpan: 1,
  fontWeight: 1,
  lineHeight: 1,
  opacity: 1,
  order: 1,
  orphans: 1,
  scale: 1,
  tabSize: 1,
  widows: 1,
  zIndex: 1,
  zoom: 1,
  WebkitLineClamp: 1,
  // SVG-related properties
  fillOpacity: 1,
  floodOpacity: 1,
  stopOpacity: 1,
  strokeDasharray: 1,
  strokeDashoffset: 1,
  strokeMiterlimit: 1,
  strokeOpacity: 1,
  strokeWidth: 1
};



// EXTERNAL MODULE: ./node_modules/@emotion/memoize/dist/emotion-memoize.esm.js
var emotion_memoize_esm = __webpack_require__(6289);
;// ./node_modules/@emotion/serialize/dist/emotion-serialize.esm.js




var isDevelopment = false;

var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;

var isCustomProperty = function isCustomProperty(property) {
  return property.charCodeAt(1) === 45;
};

var isProcessableValue = function isProcessableValue(value) {
  return value != null && typeof value !== 'boolean';
};

var processStyleName = /* #__PURE__ */(0,emotion_memoize_esm/* default */.A)(function (styleName) {
  return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});

var processStyleValue = function processStyleValue(key, value) {
  switch (key) {
    case 'animation':
    case 'animationName':
      {
        if (typeof value === 'string') {
          return value.replace(animationRegex, function (match, p1, p2) {
            cursor = {
              name: p1,
              styles: p2,
              next: cursor
            };
            return p1;
          });
        }
      }
  }

  if (unitlessKeys[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {
    return value + 'px';
  }

  return value;
};

var noComponentSelectorMessage = 'Component selectors can only be used in conjunction with ' + '@emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware ' + 'compiler transform.';

function handleInterpolation(mergedProps, registered, interpolation) {
  if (interpolation == null) {
    return '';
  }

  var componentSelector = interpolation;

  if (componentSelector.__emotion_styles !== undefined) {

    return componentSelector;
  }

  switch (typeof interpolation) {
    case 'boolean':
      {
        return '';
      }

    case 'object':
      {
        var keyframes = interpolation;

        if (keyframes.anim === 1) {
          cursor = {
            name: keyframes.name,
            styles: keyframes.styles,
            next: cursor
          };
          return keyframes.name;
        }

        var serializedStyles = interpolation;

        if (serializedStyles.styles !== undefined) {
          var next = serializedStyles.next;

          if (next !== undefined) {
            // not the most efficient thing ever but this is a pretty rare case
            // and there will be very few iterations of this generally
            while (next !== undefined) {
              cursor = {
                name: next.name,
                styles: next.styles,
                next: cursor
              };
              next = next.next;
            }
          }

          var styles = serializedStyles.styles + ";";
          return styles;
        }

        return createStringFromObject(mergedProps, registered, interpolation);
      }

    case 'function':
      {
        if (mergedProps !== undefined) {
          var previousCursor = cursor;
          var result = interpolation(mergedProps);
          cursor = previousCursor;
          return handleInterpolation(mergedProps, registered, result);
        }

        break;
      }
  } // finalize string values (regular strings and functions interpolated into css calls)


  var asString = interpolation;

  if (registered == null) {
    return asString;
  }

  var cached = registered[asString];
  return cached !== undefined ? cached : asString;
}

function createStringFromObject(mergedProps, registered, obj) {
  var string = '';

  if (Array.isArray(obj)) {
    for (var i = 0; i < obj.length; i++) {
      string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
    }
  } else {
    for (var key in obj) {
      var value = obj[key];

      if (typeof value !== 'object') {
        var asString = value;

        if (registered != null && registered[asString] !== undefined) {
          string += key + "{" + registered[asString] + "}";
        } else if (isProcessableValue(asString)) {
          string += processStyleName(key) + ":" + processStyleValue(key, asString) + ";";
        }
      } else {
        if (key === 'NO_COMPONENT_SELECTOR' && isDevelopment) {
          throw new Error(noComponentSelectorMessage);
        }

        if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
          for (var _i = 0; _i < value.length; _i++) {
            if (isProcessableValue(value[_i])) {
              string += processStyleName(key) + ":" + processStyleValue(key, value[_i]) + ";";
            }
          }
        } else {
          var interpolated = handleInterpolation(mergedProps, registered, value);

          switch (key) {
            case 'animation':
            case 'animationName':
              {
                string += processStyleName(key) + ":" + interpolated + ";";
                break;
              }

            default:
              {

                string += key + "{" + interpolated + "}";
              }
          }
        }
      }
    }
  }

  return string;
}

var labelPattern = /label:\s*([^\s;{]+)\s*(;|$)/g; // this is the cursor for keyframes
// keyframes are stored on the SerializedStyles object as a linked list

var cursor;
function serializeStyles(args, registered, mergedProps) {
  if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
    return args[0];
  }

  var stringMode = true;
  var styles = '';
  cursor = undefined;
  var strings = args[0];

  if (strings == null || strings.raw === undefined) {
    stringMode = false;
    styles += handleInterpolation(mergedProps, registered, strings);
  } else {
    var asTemplateStringsArr = strings;

    styles += asTemplateStringsArr[0];
  } // we start at 1 since we've already handled the first arg


  for (var i = 1; i < args.length; i++) {
    styles += handleInterpolation(mergedProps, registered, args[i]);

    if (stringMode) {
      var templateStringsArr = strings;

      styles += templateStringsArr[i];
    }
  } // using a global regex with .exec is stateful so lastIndex has to be reset each time


  labelPattern.lastIndex = 0;
  var identifierName = '';
  var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5

  while ((match = labelPattern.exec(styles)) !== null) {
    identifierName += '-' + match[1];
  }

  var name = murmur2(styles) + identifierName;

  return {
    name: name,
    styles: styles,
    next: cursor
  };
}




/***/ }),

/***/ 3203:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TabFloating = void 0;
const React = __webpack_require__(6540);
const Actions_1 = __webpack_require__(9103);
const TabSetNode_1 = __webpack_require__(9555);
const Types_1 = __webpack_require__(6643);
const I18nLabel_1 = __webpack_require__(300);
const Utils_1 = __webpack_require__(343);
/** @internal */
const TabFloating = (props) => {
    const { layout, selected, node, path } = props;
    const showPopout = () => {
        if (node.getWindow()) {
            node.getWindow().focus();
        }
    };
    const dockPopout = () => {
        layout.doAction(Actions_1.Actions.unFloatTab(node.getId()));
    };
    const onMouseDown = () => {
        const parent = node.getParent();
        if (parent.getType() === TabSetNode_1.TabSetNode.TYPE) {
            if (!parent.isActive()) {
                layout.doAction(Actions_1.Actions.setActiveTabset(parent.getId()));
            }
        }
    };
    const onClickFocus = (event) => {
        event.preventDefault();
        showPopout();
    };
    const onClickDock = (event) => {
        event.preventDefault();
        dockPopout();
    };
    const cm = layout.getClassName;
    const parentNode = node.getParent();
    const style = node._styleWithPosition();
    if (!selected) {
        (0, Utils_1.hideElement)(style, node.getModel().isUseVisibility());
    }
    if (parentNode instanceof TabSetNode_1.TabSetNode) {
        if (node.getModel().getMaximizedTabset() !== undefined && !parentNode.isMaximized()) {
            (0, Utils_1.hideElement)(style, node.getModel().isUseVisibility());
        }
    }
    const message = layout.i18nName(I18nLabel_1.I18nLabel.Floating_Window_Message);
    const showMessage = layout.i18nName(I18nLabel_1.I18nLabel.Floating_Window_Show_Window);
    const dockMessage = layout.i18nName(I18nLabel_1.I18nLabel.Floating_Window_Dock_Window);
    const customRenderCallback = layout.getOnRenderFloatingTabPlaceholder();
    if (customRenderCallback) {
        return (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_FLOATING), onMouseDown: onMouseDown, onTouchStart: onMouseDown, style: style }, customRenderCallback(dockPopout, showPopout)));
    }
    else {
        return (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_FLOATING), "data-layout-path": path, onMouseDown: onMouseDown, onTouchStart: onMouseDown, style: style },
            React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_FLOATING_INNER) },
                React.createElement("div", null, message),
                React.createElement("div", null,
                    React.createElement("a", { href: "#", onClick: onClickFocus }, showMessage)),
                React.createElement("div", null,
                    React.createElement("a", { href: "#", onClick: onClickDock }, dockMessage)))));
    }
};
exports.TabFloating = TabFloating;
//# sourceMappingURL=TabFloating.js.map

/***/ }),

/***/ 3391:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=IDropTarget.js.map

/***/ }),

/***/ 3404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(3072);
} else // removed by dead control flow
{}


/***/ }),

/***/ 3663:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  p2: function() { return /* binding */ JsonViewer; },
  S3: function() { return /* binding */ defineDataType; }
});

// UNUSED EXPORTS: applyValue, bigIntType, booleanType, createDataType, darkColorspace, dateType, defineEasyType, deleteValue, floatType, functionType, getPathValue, intType, isCycleReference, lightColorspace, nanType, nullType, objectType, pathValueDefaultGetter, safeStringify, stringType, undefinedType

// EXTERNAL MODULE: ./node_modules/react/jsx-runtime.js
var jsx_runtime = __webpack_require__(4848);
// EXTERNAL MODULE: ./node_modules/@mui/material/Box/Box.js + 2 modules
var Box = __webpack_require__(9067);
// EXTERNAL MODULE: ./node_modules/@mui/material/InputBase/InputBase.js + 7 modules
var InputBase = __webpack_require__(160);
// EXTERNAL MODULE: ./node_modules/@mui/material/NoSsr/NoSsr.js
var NoSsr = __webpack_require__(1675);
// EXTERNAL MODULE: ./node_modules/@mui/material/SvgIcon/SvgIcon.js + 1 modules
var SvgIcon = __webpack_require__(5765);
// EXTERNAL MODULE: ./node_modules/@mui/material/Paper/Paper.js + 2 modules
var Paper = __webpack_require__(538);
// EXTERNAL MODULE: ./node_modules/@mui/material/styles/createTheme.js + 14 modules
var createTheme = __webpack_require__(3478);
// EXTERNAL MODULE: ./node_modules/@mui/material/styles/ThemeProvider.js + 6 modules
var ThemeProvider = __webpack_require__(8950);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(6540);
;// ./node_modules/zustand/esm/vanilla.mjs
const createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set();
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const destroy = () => {
    if (( false ? 0 : void 0) !== "production") {
      console.warn(
        "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
      );
    }
    listeners.clear();
  };
  const api = { setState, getState, getInitialState, subscribe, destroy };
  const initialState = state = createState(setState, getState, api);
  return api;
};
const createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
var vanilla = (createState) => {
  if (( false ? 0 : void 0) !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'."
    );
  }
  return createStore(createState);
};



// EXTERNAL MODULE: ./node_modules/use-sync-external-store/shim/with-selector.js
var with_selector = __webpack_require__(9242);
;// ./node_modules/zustand/esm/index.mjs





const { useDebugValue } = react;
const { useSyncExternalStoreWithSelector } = with_selector;
let didWarnAboutEqualityFn = false;
const identity = (arg) => arg;
function useStore(api, selector = identity, equalityFn) {
  if (( false ? 0 : void 0) !== "production" && equalityFn && !didWarnAboutEqualityFn) {
    console.warn(
      "[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"
    );
    didWarnAboutEqualityFn = true;
  }
  const slice = useSyncExternalStoreWithSelector(
    api.subscribe,
    api.getState,
    api.getServerState || api.getInitialState,
    selector,
    equalityFn
  );
  useDebugValue(slice);
  return slice;
}
const createImpl = (createState) => {
  if (( false ? 0 : void 0) !== "production" && typeof createState !== "function") {
    console.warn(
      "[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`."
    );
  }
  const api = typeof createState === "function" ? createStore(createState) : createState;
  const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn);
  Object.assign(useBoundStore, api);
  return useBoundStore;
};
const create = (createState) => createState ? createImpl(createState) : createImpl;
var esm_react = (createState) => {
  if (( false ? 0 : void 0) !== "production") {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`."
    );
  }
  return create(createState);
};



// EXTERNAL MODULE: ./node_modules/copy-to-clipboard/index.js
var copy_to_clipboard = __webpack_require__(7965);
;// ./node_modules/@textea/json-viewer/dist/index.mjs
/// <reference types="./index.d.ts" />






function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}

const lightColorspace = {
    scheme: 'Light Theme',
    author: 'mac gainor (https://github.com/mac-s-g)',
    base00: 'rgba(0, 0, 0, 0)',
    base01: 'rgb(245, 245, 245)',
    base02: 'rgb(235, 235, 235)',
    base03: '#93a1a1',
    base04: 'rgba(0, 0, 0, 0.3)',
    base05: '#586e75',
    base06: '#073642',
    base07: '#002b36',
    base08: '#d33682',
    base09: '#cb4b16',
    base0A: '#ffd500',
    base0B: '#859900',
    base0C: '#6c71c4',
    base0D: '#586e75',
    base0E: '#2aa198',
    base0F: '#268bd2'
};
const darkColorspace = {
    scheme: 'Dark Theme',
    author: 'Chris Kempson (http://chriskempson.com)',
    base00: '#181818',
    base01: '#282828',
    base02: '#383838',
    base03: '#585858',
    base04: '#b8b8b8',
    base05: '#d8d8d8',
    base06: '#e8e8e8',
    base07: '#f8f8f8',
    base08: '#ab4642',
    base09: '#dc9656',
    base0A: '#f7ca88',
    base0B: '#a1b56c',
    base0C: '#86c1b9',
    base0D: '#7cafc2',
    base0E: '#ba8baf',
    base0F: '#a16946'
};

const DefaultKeyRenderer = ()=>null;
DefaultKeyRenderer.when = ()=>false;
const createJsonViewerStore = (props)=>{
    return create()((set, get)=>{
        var _props_rootName, _props_indentWidth, _props_keyRenderer, _props_enableAdd, _props_enableDelete, _props_enableClipboard, _props_editable, _props_onChange, _props_onCopy, _props_onSelect, _props_onAdd, _props_onDelete, _props_defaultInspectDepth, _props_defaultInspectControl, _props_maxDisplayLength, _props_groupArraysAfterLength, _props_collapseStringsAfterLength, _props_objectSortKeys, _props_quotesOnKeys, _props_displayDataTypes, _props_displaySize, _props_displayComma, _props_highlightUpdates;
        return {
            // provided by user
            rootName: (_props_rootName = props.rootName) !== null && _props_rootName !== void 0 ? _props_rootName : 'root',
            indentWidth: (_props_indentWidth = props.indentWidth) !== null && _props_indentWidth !== void 0 ? _props_indentWidth : 3,
            keyRenderer: (_props_keyRenderer = props.keyRenderer) !== null && _props_keyRenderer !== void 0 ? _props_keyRenderer : DefaultKeyRenderer,
            enableAdd: (_props_enableAdd = props.enableAdd) !== null && _props_enableAdd !== void 0 ? _props_enableAdd : false,
            enableDelete: (_props_enableDelete = props.enableDelete) !== null && _props_enableDelete !== void 0 ? _props_enableDelete : false,
            enableClipboard: (_props_enableClipboard = props.enableClipboard) !== null && _props_enableClipboard !== void 0 ? _props_enableClipboard : true,
            editable: (_props_editable = props.editable) !== null && _props_editable !== void 0 ? _props_editable : false,
            onChange: (_props_onChange = props.onChange) !== null && _props_onChange !== void 0 ? _props_onChange : ()=>{},
            onCopy: (_props_onCopy = props.onCopy) !== null && _props_onCopy !== void 0 ? _props_onCopy : undefined,
            onSelect: (_props_onSelect = props.onSelect) !== null && _props_onSelect !== void 0 ? _props_onSelect : undefined,
            onAdd: (_props_onAdd = props.onAdd) !== null && _props_onAdd !== void 0 ? _props_onAdd : undefined,
            onDelete: (_props_onDelete = props.onDelete) !== null && _props_onDelete !== void 0 ? _props_onDelete : undefined,
            defaultInspectDepth: (_props_defaultInspectDepth = props.defaultInspectDepth) !== null && _props_defaultInspectDepth !== void 0 ? _props_defaultInspectDepth : 5,
            defaultInspectControl: (_props_defaultInspectControl = props.defaultInspectControl) !== null && _props_defaultInspectControl !== void 0 ? _props_defaultInspectControl : undefined,
            maxDisplayLength: (_props_maxDisplayLength = props.maxDisplayLength) !== null && _props_maxDisplayLength !== void 0 ? _props_maxDisplayLength : 30,
            groupArraysAfterLength: (_props_groupArraysAfterLength = props.groupArraysAfterLength) !== null && _props_groupArraysAfterLength !== void 0 ? _props_groupArraysAfterLength : 100,
            collapseStringsAfterLength: props.collapseStringsAfterLength === false ? Number.MAX_VALUE : (_props_collapseStringsAfterLength = props.collapseStringsAfterLength) !== null && _props_collapseStringsAfterLength !== void 0 ? _props_collapseStringsAfterLength : 50,
            objectSortKeys: (_props_objectSortKeys = props.objectSortKeys) !== null && _props_objectSortKeys !== void 0 ? _props_objectSortKeys : false,
            quotesOnKeys: (_props_quotesOnKeys = props.quotesOnKeys) !== null && _props_quotesOnKeys !== void 0 ? _props_quotesOnKeys : true,
            displayDataTypes: (_props_displayDataTypes = props.displayDataTypes) !== null && _props_displayDataTypes !== void 0 ? _props_displayDataTypes : true,
            displaySize: (_props_displaySize = props.displaySize) !== null && _props_displaySize !== void 0 ? _props_displaySize : true,
            displayComma: (_props_displayComma = props.displayComma) !== null && _props_displayComma !== void 0 ? _props_displayComma : false,
            highlightUpdates: (_props_highlightUpdates = props.highlightUpdates) !== null && _props_highlightUpdates !== void 0 ? _props_highlightUpdates : false,
            // internal state
            inspectCache: {},
            hoverPath: null,
            colorspace: lightColorspace,
            value: props.value,
            prevValue: undefined,
            getInspectCache: (path, nestedIndex)=>{
                const target = nestedIndex !== undefined ? path.join('.') + "[".concat(nestedIndex, "]nt") : path.join('.');
                return get().inspectCache[target];
            },
            setInspectCache: (path, action, nestedIndex)=>{
                const target = nestedIndex !== undefined ? path.join('.') + "[".concat(nestedIndex, "]nt") : path.join('.');
                set((state)=>({
                        inspectCache: {
                            ...state.inspectCache,
                            [target]: typeof action === 'function' ? action(state.inspectCache[target]) : action
                        }
                    }));
            },
            setHover: (path, nestedIndex)=>{
                set({
                    hoverPath: path ? {
                        path,
                        nestedIndex
                    } : null
                });
            }
        };
    });
};
// @ts-expect-error we intentionally want to pass undefined to the context
// See https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106
const JsonViewerStoreContext = (0,react.createContext)(undefined);
JsonViewerStoreContext.Provider;
const useJsonViewerStore = (selector, equalityFn)=>{
    const store = (0,react.useContext)(JsonViewerStoreContext);
    return useStore(store, selector, equalityFn);
};

const useTextColor = ()=>{
    return useJsonViewerStore((store)=>store.colorspace.base07);
};

// reference: https://github.com/immerjs/immer/blob/main/src/utils/common.ts
const objectCtorString = Object.prototype.constructor.toString();
function isPlainObject(value) {
    if (!value || typeof value !== 'object') return false;
    const proto = Object.getPrototypeOf(value);
    if (proto === null) return true;
    const Ctor = Object.hasOwnProperty.call(proto, 'constructor') && proto.constructor;
    if (Ctor === Object) return true;
    return typeof Ctor === 'function' && Function.toString.call(Ctor) === objectCtorString;
}
function shouldShallowCopy(value) {
    if (!value) return false;
    return isPlainObject(value) || Array.isArray(value) || value instanceof Map || value instanceof Set;
}
function shallowCopy(value) {
    if (Array.isArray(value)) return Array.prototype.slice.call(value);
    if (value instanceof Set) return new Set(value);
    if (value instanceof Map) return new Map(value);
    if (typeof value === 'object' && value !== null) {
        return Object.assign({}, value);
    }
    return value;
}
function _applyValue(input, path, value) {
    let visitedMapping = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : new Map();
    if (typeof input !== 'object' || input === null) {
        if (path.length !== 0) {
            throw new Error('path is incorrect');
        }
        return value;
    }
    const shouldCopy = shouldShallowCopy(input);
    if (shouldCopy) {
        let copiedInput = visitedMapping.get(input);
        if (!copiedInput) {
            copiedInput = shallowCopy(input);
            visitedMapping.set(input, copiedInput);
        }
        input = copiedInput;
    }
    const [key, ...restPath] = path;
    if (key !== undefined) {
        if (key === '__proto__') {
            throw new TypeError('Modification of prototype is not allowed');
        }
        if (restPath.length > 0) {
            input[key] = _applyValue(input[key], restPath, value, visitedMapping);
        } else {
            input[key] = value;
        }
    }
    return input;
}
/**
 * Apply a value to a given path of an object.
 */ function applyValue(input, path, value) {
    return _applyValue(input, path, value);
}
/**
 * Delete a value from a given path of an object.
 */ function deleteValue(input, path, value) {
    if (typeof input !== 'object' || input === null) {
        if (path.length !== 0) {
            throw new Error('path is incorrect');
        }
        return value;
    }
    const shouldCopy = shouldShallowCopy(input);
    if (shouldCopy) input = shallowCopy(input);
    const [key, ...restPath] = path;
    if (key !== undefined) {
        if (key === '__proto__') {
            throw new TypeError('Modification of prototype is not allowed');
        }
        if (restPath.length > 0) {
            input[key] = deleteValue(input[key], restPath, value);
        } else {
            if (Array.isArray(input)) {
                input.splice(Number(key), 1);
            } else {
                delete input[key];
            }
        }
    }
    return input;
}
/**
 * @deprecated use `defineDataType` instead
 */ function createDataType(is, Component, Editor, PreComponent, PostComponent) {
    if (false) // removed by dead control flow
{}
    return {
        is,
        Component,
        Editor,
        PreComponent,
        PostComponent
    };
}
/**
 * Define custom data types for any data structure
 */ function defineDataType(param) {
    let { is, serialize, deserialize, Component, Editor, PreComponent, PostComponent } = param;
    return {
        is,
        serialize,
        deserialize,
        Component,
        Editor,
        PreComponent,
        PostComponent
    };
}
const isCycleReference = (root, path, value)=>{
    if (root === null || value === null) {
        return false;
    }
    if (typeof root !== 'object') {
        return false;
    }
    if (typeof value !== 'object') {
        return false;
    }
    if (Object.is(root, value) && path.length !== 0) {
        return '';
    }
    const currentPath = [];
    const arr = [
        ...path
    ];
    let currentRoot = root;
    while(currentRoot !== value || arr.length !== 0){
        if (typeof currentRoot !== 'object' || currentRoot === null) {
            return false;
        }
        if (Object.is(currentRoot, value)) {
            return currentPath.reduce((path, value, currentIndex)=>{
                if (typeof value === 'number') {
                    return path + "[".concat(value, "]");
                }
                return path + "".concat(currentIndex === 0 ? '' : '.').concat(value);
            }, '');
        }
        const target = arr.shift();
        currentPath.push(target);
        currentRoot = currentRoot[target];
    }
    return false;
};
function getValueSize(value) {
    if (value === null || undefined) {
        return 0;
    } else if (Array.isArray(value)) {
        return value.length;
    } else if (value instanceof Map || value instanceof Set) {
        return value.size;
    } else if (value instanceof Date) {
        return 1;
    } else if (typeof value === 'object') {
        return Object.keys(value).length;
    } else if (typeof value === 'string') {
        return value.length;
    }
    return 1;
}
function segmentArray(arr, size) {
    const result = [];
    let index = 0;
    while(index < arr.length){
        result.push(arr.slice(index, index + size));
        index += size;
    }
    return result;
}
/**
 * A safe version of `JSON.stringify` that handles circular references and BigInts.
 *
 * *This function might be changed in the future to support more types. Use it with caution.*
 *
 * @param obj A JavaScript value, usually an object or array, to be converted.
 * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
 * @returns
 */ function safeStringify(obj, space) {
    const seenValues = [];
    function replacer(key, value) {
        // https://github.com/GoogleChromeLabs/jsbi/issues/30
        if (typeof value === 'bigint') return value.toString();
        // Map and Set are not supported by JSON.stringify
        if (value instanceof Map) {
            if ('toJSON' in value && typeof value.toJSON === 'function') return value.toJSON();
            if (value.size === 0) return {};
            if (seenValues.includes(value)) return '[Circular]';
            seenValues.push(value);
            const entries = Array.from(value.entries());
            if (entries.every((param)=>{
                let [key] = param;
                return typeof key === 'string' || typeof key === 'number';
            })) {
                return Object.fromEntries(entries);
            }
            // if keys are not string or number, we can't convert to object
            // fallback to default behavior
            return {};
        }
        if (value instanceof Set) {
            if ('toJSON' in value && typeof value.toJSON === 'function') return value.toJSON();
            if (seenValues.includes(value)) return '[Circular]';
            seenValues.push(value);
            return Array.from(value.values());
        }
        // https://stackoverflow.com/a/72457899
        if (typeof value === 'object' && value !== null && Object.keys(value).length) {
            const stackSize = seenValues.length;
            if (stackSize) {
                // clean up expired references
                for(let n = stackSize - 1; n >= 0 && seenValues[n][key] !== value; --n){
                    seenValues.pop();
                }
                if (seenValues.includes(value)) return '[Circular]';
            }
            seenValues.push(value);
        }
        return value;
    }
    return JSON.stringify(obj, replacer, space);
}
async function copyString(value) {
    if ('clipboard' in navigator) {
        try {
            await navigator.clipboard.writeText(value);
        } catch  {
        // When navigator.clipboard throws an error, fallback to copy-to-clipboard package
        }
    }
    // fallback to copy-to-clipboard when navigator.clipboard is not available
    copy_to_clipboard(value);
}
function pathValueDefaultGetter(value, key) {
    if (value === null || value === undefined) {
        return null;
    }
    if (value instanceof Map || value instanceof WeakMap) {
        return value.get(key);
    }
    if (value instanceof Set) {
        return Array.from(value)[key];
    }
    if (value instanceof WeakSet) {
        throw new Error('WeakSet is not supported');
    }
    if (Array.isArray(value)) {
        return value[Number(key)];
    }
    if (typeof value === 'object') {
        return value[key];
    }
    return null;
}
/**
 * Get the value at a given path in an object.
 * Passing custom getters allows you to handle custom data structures.
 * @experimental This function is not yet stable and may change in the future.
 */ function getPathValue(obj, path) {
    let customGetters = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
    try {
        // @ts-ignore
        return path.reduce((acc, key, index)=>{
            if (acc === null || acc === undefined) {
                console.error('Invalid path or value encountered at path', path.slice(0, index));
                throw new Error('Invalid path or value encountered');
            }
            for (const handler of customGetters){
                const currentPath = path.slice(0, index + 1);
                if (handler.is(acc, currentPath)) {
                    return handler.handler(acc, key);
                }
            }
            return pathValueDefaultGetter(acc, key);
        }, obj);
    } catch (error) {
        console.error(error);
        return null // or throw error?
        ;
    }
}

/**
 * useClipboard hook accepts one argument options in which copied status timeout duration is defined (defaults to 2000). Hook returns object with properties:
 * - copy – function to copy value to clipboard
 * - copied – value that indicates that copy handler was called less than options.timeout ms ago
 * - reset – function to clear timeout and reset copied to false
 */ function useClipboard() {
    let { timeout = 2000 } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    const [copied, setCopied] = (0,react.useState)(false);
    const copyTimeout = (0,react.useRef)(null);
    const handleCopyResult = (0,react.useCallback)((value)=>{
        const current = copyTimeout.current;
        if (current) {
            window.clearTimeout(current);
        }
        copyTimeout.current = window.setTimeout(()=>setCopied(false), timeout);
        setCopied(value);
    }, [
        timeout
    ]);
    const onCopy = useJsonViewerStore((store)=>store.onCopy);
    const copy = (0,react.useCallback)(async (path, value)=>{
        if (typeof onCopy === 'function') {
            try {
                await onCopy(path, value, copyString);
                handleCopyResult(true);
            } catch (error) {
                console.error("error when copy ".concat(path.length === 0 ? 'src' : "src[".concat(path.join('.')), "]"), error);
            }
        } else {
            try {
                const valueToCopy = safeStringify(typeof value === 'function' ? value.toString() : value, '  ');
                await copyString(valueToCopy);
                handleCopyResult(true);
            } catch (error) {
                console.error("error when copy ".concat(path.length === 0 ? 'src' : "src[".concat(path.join('.')), "]"), error);
            }
        }
    }, [
        handleCopyResult,
        onCopy
    ]);
    const reset = (0,react.useCallback)(()=>{
        setCopied(false);
        if (copyTimeout.current) {
            clearTimeout(copyTimeout.current);
        }
    }, []);
    return {
        copy,
        reset,
        copied
    };
}

function useIsCycleReference(path, value) {
    const rootValue = useJsonViewerStore((store)=>store.value);
    return (0,react.useMemo)(()=>isCycleReference(rootValue, path, value), [
        path,
        value,
        rootValue
    ]);
}

function useInspect(path, value, nestedIndex) {
    const depth = path.length;
    const isTrap = useIsCycleReference(path, value);
    const getInspectCache = useJsonViewerStore((store)=>store.getInspectCache);
    const setInspectCache = useJsonViewerStore((store)=>store.setInspectCache);
    const defaultInspectDepth = useJsonViewerStore((store)=>store.defaultInspectDepth);
    const defaultInspectControl = useJsonViewerStore((store)=>store.defaultInspectControl);
    (0,react.useEffect)(()=>{
        const inspect = getInspectCache(path, nestedIndex);
        if (inspect !== undefined) {
            return;
        }
        // item with nestedIndex should not be inspected
        if (nestedIndex !== undefined) {
            setInspectCache(path, false, nestedIndex);
            return;
        }
        // do not inspect when it is a cycle reference, otherwise there will have a loop
        const shouldInspect = isTrap ? false : typeof defaultInspectControl === 'function' ? defaultInspectControl(path, value) : depth < defaultInspectDepth;
        setInspectCache(path, shouldInspect);
    }, [
        defaultInspectDepth,
        defaultInspectControl,
        depth,
        getInspectCache,
        isTrap,
        nestedIndex,
        path,
        value,
        setInspectCache
    ]);
    const [inspect, set] = (0,react.useState)(()=>{
        const shouldInspect = getInspectCache(path, nestedIndex);
        if (shouldInspect !== undefined) {
            return shouldInspect;
        }
        if (nestedIndex !== undefined) {
            return false;
        }
        return isTrap ? false : typeof defaultInspectControl === 'function' ? defaultInspectControl(path, value) : depth < defaultInspectDepth;
    });
    const setInspect = (0,react.useCallback)((apply)=>{
        set((oldState)=>{
            const newState = typeof apply === 'boolean' ? apply : apply(oldState);
            setInspectCache(path, newState, nestedIndex);
            return newState;
        });
    }, [
        nestedIndex,
        path,
        setInspectCache
    ]);
    return [
        inspect,
        setInspect
    ];
}

const DataBox = (props)=>/*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
        component: "div",
        ...props,
        sx: {
            display: 'inline-block',
            ...props.sx
        }
    });

const DataTypeLabel = (param)=>{
    let { dataType, enable = true } = param;
    if (!enable) return null;
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(DataBox, {
        className: "data-type-label",
        sx: {
            mx: 0.5,
            fontSize: '0.7rem',
            opacity: 0.8,
            userSelect: 'none'
        },
        children: dataType
    });
};

/**
 * Enhanced version of `defineDataType` that creates a `DataType` with editor and a optional type label.
 * It will take care of the color and all the necessary props.
 *
 * *All of the built-in data types are defined with this function.*
 *
 * @param config.type The type name.
 * @param config.colorKey The color key in the colorspace. ('base00' - 'base0F')
 * @param config.displayTypeLabel Whether to display the type label.
 * @param config.Renderer The component to render the value.
 */ function defineEasyType(param) {
    let { is, serialize, deserialize, type, colorKey, displayTypeLabel = true, Renderer } = param;
    const Render = /*#__PURE__*/ (0,react.memo)(Renderer);
    const EasyType = (props)=>{
        const storeDisplayDataTypes = useJsonViewerStore((store)=>store.displayDataTypes);
        const color = useJsonViewerStore((store)=>store.colorspace[colorKey]);
        const onSelect = useJsonViewerStore((store)=>store.onSelect);
        return /*#__PURE__*/ (0,jsx_runtime.jsxs)(DataBox, {
            onClick: ()=>onSelect === null || onSelect === void 0 ? void 0 : onSelect(props.path, props.value),
            sx: {
                color
            },
            children: [
                displayTypeLabel && storeDisplayDataTypes && /*#__PURE__*/ (0,jsx_runtime.jsx)(DataTypeLabel, {
                    dataType: type
                }),
                /*#__PURE__*/ (0,jsx_runtime.jsx)(DataBox, {
                    className: "".concat(type, "-value"),
                    children: /*#__PURE__*/ (0,jsx_runtime.jsx)(Render, {
                        path: props.path,
                        inspect: props.inspect,
                        setInspect: props.setInspect,
                        value: props.value,
                        prevValue: props.prevValue
                    })
                })
            ]
        });
    };
    EasyType.displayName = "easy-".concat(type, "-type");
    if (!serialize || !deserialize) {
        return {
            is,
            Component: EasyType
        };
    }
    const EasyTypeEditor = (param)=>{
        let { value, setValue, abortEditing, commitEditing } = param;
        const color = useJsonViewerStore((store)=>store.colorspace[colorKey]);
        const handleKeyDown = (0,react.useCallback)((event)=>{
            if (event.key === 'Enter') {
                event.preventDefault();
                commitEditing(value);
            }
            if (event.key === 'Escape') {
                event.preventDefault();
                abortEditing();
            }
        }, [
            abortEditing,
            commitEditing,
            value
        ]);
        const handleChange = (0,react.useCallback)((event)=>{
            setValue(event.target.value);
        }, [
            setValue
        ]);
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(InputBase/* default */.Ay, {
            autoFocus: true,
            value: value,
            onChange: handleChange,
            onKeyDown: handleKeyDown,
            size: "small",
            multiline: true,
            sx: {
                color,
                padding: 0.5,
                borderStyle: 'solid',
                borderColor: 'black',
                borderWidth: 1,
                fontSize: '0.8rem',
                fontFamily: 'monospace',
                display: 'inline-flex'
            }
        });
    };
    EasyTypeEditor.displayName = "easy-".concat(type, "-type-editor");
    return {
        is,
        serialize,
        deserialize,
        Component: EasyType,
        Editor: EasyTypeEditor
    };
}

const booleanType = defineEasyType({
    is: (value)=>typeof value === 'boolean',
    type: 'bool',
    colorKey: 'base0E',
    serialize: (value)=>value.toString(),
    deserialize: (value)=>{
        if (value === 'true') return true;
        if (value === 'false') return false;
        throw new Error('Invalid boolean value');
    },
    Renderer: (param)=>{
        let { value } = param;
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
            children: value ? 'true' : 'false'
        });
    }
});

const displayOptions = {
    weekday: 'short',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
};
const dateType = defineEasyType({
    is: (value)=>value instanceof Date,
    type: 'date',
    colorKey: 'base0D',
    Renderer: (param)=>{
        let { value } = param;
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
            children: value.toLocaleTimeString('en-us', displayOptions)
        });
    }
});

const functionBody = (func)=>{
    const funcString = func.toString();
    let isUsualFunction = true;
    const parenthesisPos = funcString.indexOf(')');
    const arrowPos = funcString.indexOf('=>');
    if (arrowPos !== -1 && arrowPos > parenthesisPos) {
        isUsualFunction = false;
    }
    if (isUsualFunction) {
        return funcString.substring(funcString.indexOf('{', parenthesisPos) + 1, funcString.lastIndexOf('}'));
    }
    return funcString.substring(funcString.indexOf('=>') + 2);
};
const functionName = (func)=>{
    const funcString = func.toString();
    const isUsualFunction = funcString.indexOf('function') !== -1;
    if (isUsualFunction) {
        return funcString.substring(8, funcString.indexOf('{')).trim();
    }
    return funcString.substring(0, funcString.indexOf('=>') + 2).trim();
};
const lb = '{';
const rb = '}';
const PreFunctionType = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsxs)(NoSsr/* default */.A, {
        children: [
            /*#__PURE__*/ (0,jsx_runtime.jsx)(DataTypeLabel, {
                dataType: "function"
            }),
            /*#__PURE__*/ (0,jsx_runtime.jsxs)(Box/* default */.A, {
                component: "span",
                className: "data-function-start",
                sx: {
                    letterSpacing: 0.5
                },
                children: [
                    functionName(props.value),
                    ' ',
                    lb
                ]
            })
        ]
    });
};
const PostFunctionType = ()=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(NoSsr/* default */.A, {
        children: /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
            component: "span",
            className: "data-function-end",
            children: rb
        })
    });
};
const FunctionType = (props)=>{
    const functionColor = useJsonViewerStore((store)=>store.colorspace.base05);
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(NoSsr/* default */.A, {
        children: /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
            className: "data-function",
            sx: {
                display: props.inspect ? 'block' : 'inline-block',
                pl: props.inspect ? 2 : 0,
                color: functionColor
            },
            children: props.inspect ? functionBody(props.value) : /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                component: "span",
                className: "data-function-body",
                onClick: ()=>props.setInspect(true),
                sx: {
                    '&:hover': {
                        cursor: 'pointer'
                    },
                    padding: 0.5
                },
                children: "…"
            })
        })
    });
};
const functionType = {
    is: (value)=>typeof value === 'function',
    Component: FunctionType,
    PreComponent: PreFunctionType,
    PostComponent: PostFunctionType
};

const nullType = defineEasyType({
    is: (value)=>value === null,
    type: 'null',
    colorKey: 'base08',
    displayTypeLabel: false,
    Renderer: ()=>{
        const backgroundColor = useJsonViewerStore((store)=>store.colorspace.base02);
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
            sx: {
                fontSize: '0.8rem',
                backgroundColor,
                fontWeight: 'bold',
                borderRadius: '3px',
                padding: '0.5px 2px'
            },
            children: "NULL"
        });
    }
});

const isInt = (n)=>n % 1 === 0;
const nanType = defineEasyType({
    is: (value)=>typeof value === 'number' && isNaN(value),
    type: 'NaN',
    colorKey: 'base08',
    displayTypeLabel: false,
    serialize: ()=>'NaN',
    // allow deserialize the value back to number
    deserialize: (value)=>parseFloat(value),
    Renderer: ()=>{
        const backgroundColor = useJsonViewerStore((store)=>store.colorspace.base02);
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
            sx: {
                backgroundColor,
                fontSize: '0.8rem',
                fontWeight: 'bold',
                borderRadius: '3px',
                padding: '0.5px 2px'
            },
            children: "NaN"
        });
    }
});
const floatType = defineEasyType({
    is: (value)=>typeof value === 'number' && !isInt(value) && !isNaN(value),
    type: 'float',
    colorKey: 'base0B',
    serialize: (value)=>value.toString(),
    deserialize: (value)=>parseFloat(value),
    Renderer: (param)=>{
        let { value } = param;
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
            children: value
        });
    }
});
const intType = defineEasyType({
    is: (value)=>typeof value === 'number' && isInt(value),
    type: 'int',
    colorKey: 'base0F',
    serialize: (value)=>value.toString(),
    // allow deserialize the value to float
    deserialize: (value)=>parseFloat(value),
    Renderer: (param)=>{
        let { value } = param;
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
            children: value
        });
    }
});
const bigIntType = defineEasyType({
    is: (value)=>typeof value === 'bigint',
    type: 'bigint',
    colorKey: 'base0F',
    serialize: (value)=>value.toString(),
    deserialize: (value)=>BigInt(value.replace(/\D/g, '')),
    Renderer: (param)=>{
        let { value } = param;
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
            children: "".concat(value, "n")
        });
    }
});

const BaseIcon = (param)=>{
    let { d, ...props } = param;
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(SvgIcon/* default */.A, {
        ...props,
        children: /*#__PURE__*/ (0,jsx_runtime.jsx)("path", {
            d: d
        })
    });
};
const AddBox = 'M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14zm-8-2h2v-4h4v-2h-4V7h-2v4H7v2h4z';
const Check = 'M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z';
const ChevronRight = 'M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z';
const CircularArrows = 'M 12 2 C 10.615 1.998 9.214625 2.2867656 7.890625 2.8847656 L 8.9003906 4.6328125 C 9.9043906 4.2098125 10.957 3.998 12 4 C 15.080783 4 17.738521 5.7633175 19.074219 8.3222656 L 17.125 9 L 21.25 11 L 22.875 7 L 20.998047 7.6523438 C 19.377701 4.3110398 15.95585 2 12 2 z M 6.5097656 4.4882812 L 2.2324219 5.0820312 L 3.734375 6.3808594 C 1.6515335 9.4550558 1.3615962 13.574578 3.3398438 17 C 4.0308437 18.201 4.9801562 19.268234 6.1601562 20.115234 L 7.1699219 18.367188 C 6.3019219 17.710187 5.5922656 16.904 5.0722656 16 C 3.5320014 13.332354 3.729203 10.148679 5.2773438 7.7128906 L 6.8398438 9.0625 L 6.5097656 4.4882812 z M 19.929688 13 C 19.794687 14.08 19.450734 15.098 18.927734 16 C 17.386985 18.668487 14.531361 20.090637 11.646484 19.966797 L 12.035156 17.9375 L 8.2402344 20.511719 L 10.892578 23.917969 L 11.265625 21.966797 C 14.968963 22.233766 18.681899 20.426323 20.660156 17 C 21.355156 15.801 21.805219 14.445 21.949219 13 L 19.929688 13 z';
const Close = 'M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z';
const ContentCopy = 'M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z';
const Edit = 'M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z';
const ExpandMore = 'M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z';
const Delete = 'M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM8 9h8v10H8zm7.5-5l-1-1h-5l-1 1H5v2h14V4z';
const AddBoxIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: AddBox,
        ...props
    });
};
const CheckIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: Check,
        ...props
    });
};
const ChevronRightIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: ChevronRight,
        ...props
    });
};
const CircularArrowsIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: CircularArrows,
        ...props
    });
};
const CloseIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: Close,
        ...props
    });
};
const ContentCopyIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: ContentCopy,
        ...props
    });
};
const EditIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: Edit,
        ...props
    });
};
const ExpandMoreIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: ExpandMore,
        ...props
    });
};
const DeleteIcon = (props)=>{
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(BaseIcon, {
        d: Delete,
        ...props
    });
};

const objectLb = '{';
const arrayLb = '[';
const objectRb = '}';
const arrayRb = ']';
function inspectMetadata(value) {
    const length = getValueSize(value);
    let name = '';
    if (value instanceof Map || value instanceof Set) {
        name = value[Symbol.toStringTag];
    }
    if (Object.prototype.hasOwnProperty.call(value, Symbol.toStringTag)) {
        name = value[Symbol.toStringTag];
    }
    return "".concat(length, " Items").concat(name ? " (".concat(name, ")") : '');
}
const PreObjectType = (props)=>{
    const metadataColor = useJsonViewerStore((store)=>store.colorspace.base04);
    const textColor = useTextColor();
    const isArrayLike = (0,react.useMemo)(()=>Array.isArray(props.value) || props.value instanceof Set, [
        props.value
    ]);
    const isEmptyValue = (0,react.useMemo)(()=>getValueSize(props.value) === 0, [
        props.value
    ]);
    const sizeOfValue = (0,react.useMemo)(()=>inspectMetadata(props.value), [
        props.value
    ]);
    const displaySize = useJsonViewerStore((store)=>store.displaySize);
    const shouldDisplaySize = (0,react.useMemo)(()=>typeof displaySize === 'function' ? displaySize(props.path, props.value) : displaySize, [
        displaySize,
        props.path,
        props.value
    ]);
    const isTrap = useIsCycleReference(props.path, props.value);
    return /*#__PURE__*/ (0,jsx_runtime.jsxs)(Box/* default */.A, {
        component: "span",
        className: "data-object-start",
        sx: {
            letterSpacing: 0.5
        },
        children: [
            isArrayLike ? arrayLb : objectLb,
            shouldDisplaySize && props.inspect && !isEmptyValue && /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                component: "span",
                sx: {
                    pl: 0.5,
                    fontStyle: 'italic',
                    color: metadataColor,
                    userSelect: 'none'
                },
                children: sizeOfValue
            }),
            isTrap && !props.inspect && /*#__PURE__*/ (0,jsx_runtime.jsxs)(jsx_runtime.Fragment, {
                children: [
                    /*#__PURE__*/ (0,jsx_runtime.jsx)(CircularArrowsIcon, {
                        sx: {
                            fontSize: 12,
                            color: textColor,
                            mx: 0.5
                        }
                    }),
                    /*#__PURE__*/ (0,jsx_runtime.jsx)(DataBox, {
                        sx: {
                            cursor: 'pointer',
                            userSelect: 'none'
                        },
                        children: isTrap
                    })
                ]
            })
        ]
    });
};
const PostObjectType = (props)=>{
    const metadataColor = useJsonViewerStore((store)=>store.colorspace.base04);
    const textColor = useTextColor();
    const isArrayLike = (0,react.useMemo)(()=>Array.isArray(props.value) || props.value instanceof Set, [
        props.value
    ]);
    const isEmptyValue = (0,react.useMemo)(()=>getValueSize(props.value) === 0, [
        props.value
    ]);
    const sizeOfValue = (0,react.useMemo)(()=>inspectMetadata(props.value), [
        props.value
    ]);
    const displaySize = useJsonViewerStore((store)=>store.displaySize);
    const shouldDisplaySize = (0,react.useMemo)(()=>typeof displaySize === 'function' ? displaySize(props.path, props.value) : displaySize, [
        displaySize,
        props.path,
        props.value
    ]);
    return /*#__PURE__*/ (0,jsx_runtime.jsxs)(Box/* default */.A, {
        component: "span",
        className: "data-object-end",
        sx: {
            lineHeight: 1.5,
            color: textColor,
            letterSpacing: 0.5,
            opacity: 0.8
        },
        children: [
            isArrayLike ? arrayRb : objectRb,
            shouldDisplaySize && (isEmptyValue || !props.inspect) ? /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                component: "span",
                sx: {
                    pl: 0.5,
                    fontStyle: 'italic',
                    color: metadataColor,
                    userSelect: 'none'
                },
                children: sizeOfValue
            }) : null
        ]
    });
};
function getIterator(value) {
    return typeof (value === null || value === void 0 ? void 0 : value[Symbol.iterator]) === 'function';
}
const ObjectType = (props)=>{
    const keyColor = useTextColor();
    const borderColor = useJsonViewerStore((store)=>store.colorspace.base02);
    const groupArraysAfterLength = useJsonViewerStore((store)=>store.groupArraysAfterLength);
    const isTrap = useIsCycleReference(props.path, props.value);
    const [displayLength, setDisplayLength] = (0,react.useState)(useJsonViewerStore((store)=>store.maxDisplayLength));
    const objectSortKeys = useJsonViewerStore((store)=>store.objectSortKeys);
    const elements = (0,react.useMemo)(()=>{
        if (!props.inspect) {
            return null;
        }
        const value = props.value;
        const iterator = getIterator(value);
        // Array also has iterator, we skip it and treat it as an array as normal.
        if (iterator && !Array.isArray(value)) {
            const elements = [];
            if (value instanceof Map) {
                const lastIndex = value.size - 1;
                let index = 0;
                value.forEach((value, k)=>{
                    // fixme: key might be a object, array, or any value for the `Map<any, any>`
                    const key = k.toString();
                    const path = [
                        ...props.path,
                        key
                    ];
                    elements.push(/*#__PURE__*/ (0,jsx_runtime.jsx)(DataKeyPair, {
                        path: path,
                        value: value,
                        prevValue: props.prevValue instanceof Map ? props.prevValue.get(k) : undefined,
                        editable: false,
                        last: index === lastIndex
                    }, key));
                    index++;
                });
            } else {
                // iterate with iterator func
                const iterator = value[Symbol.iterator]();
                let result = iterator.next();
                let count = 0;
                while(true){
                    const nextResult = iterator.next();
                    var _nextResult_done;
                    elements.push(/*#__PURE__*/ (0,jsx_runtime.jsx)(DataKeyPair, {
                        path: [
                            ...props.path,
                            "iterator:".concat(count)
                        ],
                        value: result.value,
                        nestedIndex: count,
                        editable: false,
                        last: (_nextResult_done = nextResult.done) !== null && _nextResult_done !== void 0 ? _nextResult_done : false
                    }, count));
                    if (nextResult.done) {
                        break;
                    }
                    count++;
                    result = nextResult;
                }
            }
            return elements;
        }
        if (Array.isArray(value)) {
            const lastIndex = value.length - 1;
            // unknown[]
            if (value.length <= groupArraysAfterLength) {
                const elements = value.slice(0, displayLength).map((value, _index)=>{
                    const index = props.nestedIndex ? props.nestedIndex * groupArraysAfterLength + _index : _index;
                    const path = [
                        ...props.path,
                        index
                    ];
                    return /*#__PURE__*/ (0,jsx_runtime.jsx)(DataKeyPair, {
                        path: path,
                        value: value,
                        prevValue: Array.isArray(props.prevValue) ? props.prevValue[index] : undefined,
                        last: _index === lastIndex
                    }, index);
                });
                if (value.length > displayLength) {
                    const rest = value.length - displayLength;
                    elements.push(/*#__PURE__*/ (0,jsx_runtime.jsxs)(DataBox, {
                        sx: {
                            cursor: 'pointer',
                            lineHeight: 1.5,
                            color: keyColor,
                            letterSpacing: 0.5,
                            opacity: 0.8,
                            userSelect: 'none'
                        },
                        onClick: ()=>setDisplayLength((length)=>length * 2),
                        children: [
                            "hidden ",
                            rest,
                            " items…"
                        ]
                    }, "last"));
                }
                return elements;
            }
            const elements = segmentArray(value, groupArraysAfterLength);
            const prevElements = Array.isArray(props.prevValue) ? segmentArray(props.prevValue, groupArraysAfterLength) : undefined;
            const elementsLastIndex = elements.length - 1;
            return elements.map((list, index)=>{
                return /*#__PURE__*/ (0,jsx_runtime.jsx)(DataKeyPair, {
                    path: props.path,
                    value: list,
                    nestedIndex: index,
                    prevValue: prevElements === null || prevElements === void 0 ? void 0 : prevElements[index],
                    last: index === elementsLastIndex
                }, index);
            });
        }
        // object
        let entries = Object.entries(value);
        if (objectSortKeys) {
            entries = objectSortKeys === true ? entries.sort((param, param1)=>{
                let [a] = param, [b] = param1;
                return a.localeCompare(b);
            }) : entries.sort((param, param1)=>{
                let [a] = param, [b] = param1;
                return objectSortKeys(a, b);
            });
        }
        const lastIndex = entries.length - 1;
        const elements = entries.slice(0, displayLength).map((param, index)=>{
            let [key, value] = param;
            var _props_prevValue;
            const path = [
                ...props.path,
                key
            ];
            return /*#__PURE__*/ (0,jsx_runtime.jsx)(DataKeyPair, {
                path: path,
                value: value,
                prevValue: (_props_prevValue = props.prevValue) === null || _props_prevValue === void 0 ? void 0 : _props_prevValue[key],
                last: index === lastIndex
            }, key);
        });
        if (entries.length > displayLength) {
            const rest = entries.length - displayLength;
            elements.push(/*#__PURE__*/ (0,jsx_runtime.jsxs)(DataBox, {
                sx: {
                    cursor: 'pointer',
                    lineHeight: 1.5,
                    color: keyColor,
                    letterSpacing: 0.5,
                    opacity: 0.8,
                    userSelect: 'none'
                },
                onClick: ()=>setDisplayLength((length)=>length * 2),
                children: [
                    "hidden ",
                    rest,
                    " items…"
                ]
            }, "last"));
        }
        return elements;
    }, [
        props.inspect,
        props.value,
        props.prevValue,
        props.path,
        props.nestedIndex,
        groupArraysAfterLength,
        displayLength,
        keyColor,
        objectSortKeys
    ]);
    const marginLeft = props.inspect ? 0.6 : 0;
    const width = useJsonViewerStore((store)=>store.indentWidth);
    const indentWidth = props.inspect ? width - marginLeft : width;
    const isEmptyValue = (0,react.useMemo)(()=>getValueSize(props.value) === 0, [
        props.value
    ]);
    if (isEmptyValue) {
        return null;
    }
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
        className: "data-object",
        sx: {
            display: props.inspect ? 'block' : 'inline-block',
            pl: props.inspect ? indentWidth - 0.6 : 0,
            marginLeft,
            color: keyColor,
            borderLeft: props.inspect ? "1px solid ".concat(borderColor) : 'none'
        },
        children: props.inspect ? elements : !isTrap && /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
            component: "span",
            className: "data-object-body",
            onClick: ()=>props.setInspect(true),
            sx: {
                '&:hover': {
                    cursor: 'pointer'
                },
                padding: 0.5,
                userSelect: 'none'
            },
            children: "…"
        })
    });
};
const objectType = {
    is: (value)=>typeof value === 'object',
    Component: ObjectType,
    PreComponent: PreObjectType,
    PostComponent: PostObjectType
};

const stringType = defineEasyType({
    is: (value)=>typeof value === 'string',
    type: 'string',
    colorKey: 'base09',
    serialize: (value)=>value,
    deserialize: (value)=>value,
    Renderer: (props)=>{
        const [showRest, setShowRest] = (0,react.useState)(false);
        const collapseStringsAfterLength = useJsonViewerStore((store)=>store.collapseStringsAfterLength);
        const value = showRest ? props.value : props.value.slice(0, collapseStringsAfterLength);
        const hasRest = props.value.length > collapseStringsAfterLength;
        return /*#__PURE__*/ (0,jsx_runtime.jsxs)(Box/* default */.A, {
            component: "span",
            sx: {
                overflowWrap: 'anywhere',
                cursor: hasRest ? 'pointer' : 'inherit'
            },
            onClick: ()=>{
                var _window_getSelection;
                if (((_window_getSelection = window.getSelection()) === null || _window_getSelection === void 0 ? void 0 : _window_getSelection.type) === 'Range') {
                    return;
                }
                if (hasRest) {
                    setShowRest((value)=>!value);
                }
            },
            children: [
                '"',
                value,
                hasRest && !showRest && /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                    component: "span",
                    sx: {
                        padding: 0.5
                    },
                    children: "…"
                }),
                '"'
            ]
        });
    }
});

const undefinedType = defineEasyType({
    is: (value)=>value === undefined,
    type: 'undefined',
    colorKey: 'base05',
    displayTypeLabel: false,
    Renderer: ()=>{
        const backgroundColor = useJsonViewerStore((store)=>store.colorspace.base02);
        return /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
            sx: {
                fontSize: '0.7rem',
                backgroundColor,
                borderRadius: '3px',
                padding: '0.5px 2px'
            },
            children: "undefined"
        });
    }
});

function memorizeDataType(dataType) {
    function compare(prevProps, nextProps) {
        var _prevProps_path, _nextProps_path;
        return Object.is(prevProps.value, nextProps.value) && prevProps.inspect && nextProps.inspect && ((_prevProps_path = prevProps.path) === null || _prevProps_path === void 0 ? void 0 : _prevProps_path.join('.')) === ((_nextProps_path = nextProps.path) === null || _nextProps_path === void 0 ? void 0 : _nextProps_path.join('.'));
    }
    dataType.Component = /*#__PURE__*/ (0,react.memo)(dataType.Component, compare);
    if (dataType.Editor) {
        dataType.Editor = /*#__PURE__*/ (0,react.memo)(dataType.Editor, function compare(prevProps, nextProps) {
            return Object.is(prevProps.value, nextProps.value);
        });
    }
    if (dataType.PreComponent) {
        dataType.PreComponent = /*#__PURE__*/ (0,react.memo)(dataType.PreComponent, compare);
    }
    if (dataType.PostComponent) {
        dataType.PostComponent = /*#__PURE__*/ (0,react.memo)(dataType.PostComponent, compare);
    }
    return dataType;
}
const predefinedTypes = [
    memorizeDataType(booleanType),
    memorizeDataType(dateType),
    memorizeDataType(nullType),
    memorizeDataType(undefinedType),
    memorizeDataType(stringType),
    memorizeDataType(functionType),
    memorizeDataType(nanType),
    memorizeDataType(intType),
    memorizeDataType(floatType),
    memorizeDataType(bigIntType)
];
const createTypeRegistryStore = ()=>{
    return createStore()((set)=>({
            registry: predefinedTypes,
            registerTypes: (setState)=>{
                set((state)=>({
                        registry: typeof setState === 'function' ? setState(state.registry) : setState
                    }));
            }
        }));
};
// @ts-expect-error we intentionally want to pass undefined to the context
// See https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106
const TypeRegistryStoreContext = /*#__PURE__*/ (0,react.createContext)(undefined);
TypeRegistryStoreContext.Provider;
const useTypeRegistryStore = (selector, equalityFn)=>{
    const store = (0,react.useContext)(TypeRegistryStoreContext);
    return useStore(store, selector, equalityFn);
};
function matchTypeComponents(value, path, registry) {
    let potential;
    for (const T of registry){
        if (T.is(value, path)) {
            potential = T;
        }
    }
    if (potential === undefined) {
        if (typeof value === 'object') {
            return objectType;
        }
        throw new Error("No type matched for value: ".concat(value));
    }
    return potential;
}
function useTypeComponents(value, path) {
    const registry = useTypeRegistryStore((store)=>store.registry);
    return (0,react.useMemo)(()=>matchTypeComponents(value, path, registry), [
        value,
        path,
        registry
    ]);
}

const IconBox = (props)=>/*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
        component: "span",
        ...props,
        sx: {
            cursor: 'pointer',
            paddingLeft: '0.7rem',
            ...props.sx
        }
    });
const DataKeyPair = (props)=>{
    const { value, prevValue, path, nestedIndex, last } = props;
    const { Component, PreComponent, PostComponent, Editor, serialize, deserialize } = useTypeComponents(value, path);
    var _props_editable;
    const propsEditable = (_props_editable = props.editable) !== null && _props_editable !== void 0 ? _props_editable : undefined;
    const storeEditable = useJsonViewerStore((store)=>store.editable);
    const editable = (0,react.useMemo)(()=>{
        if (storeEditable === false) {
            return false;
        }
        if (propsEditable === false) {
            // props.editable is false which means we cannot provide the suitable way to edit it
            return false;
        }
        if (typeof storeEditable === 'function') {
            return !!storeEditable(path, value);
        }
        return storeEditable;
    }, [
        path,
        propsEditable,
        storeEditable,
        value
    ]);
    const [tempValue, setTempValue] = (0,react.useState)('');
    const depth = path.length;
    const key = path[depth - 1];
    const hoverPath = useJsonViewerStore((store)=>store.hoverPath);
    const isHover = (0,react.useMemo)(()=>{
        return hoverPath && path.every((value, index)=>value === hoverPath.path[index] && nestedIndex === hoverPath.nestedIndex);
    }, [
        hoverPath,
        path,
        nestedIndex
    ]);
    const setHover = useJsonViewerStore((store)=>store.setHover);
    const root = useJsonViewerStore((store)=>store.value);
    const [inspect, setInspect] = useInspect(path, value, nestedIndex);
    const [editing, setEditing] = (0,react.useState)(false);
    const onChange = useJsonViewerStore((store)=>store.onChange);
    const keyColor = useTextColor();
    const numberKeyColor = useJsonViewerStore((store)=>store.colorspace.base0C);
    const highlightColor = useJsonViewerStore((store)=>store.colorspace.base0A);
    const displayComma = useJsonViewerStore((store)=>store.displayComma);
    const quotesOnKeys = useJsonViewerStore((store)=>store.quotesOnKeys);
    const rootName = useJsonViewerStore((store)=>store.rootName);
    const isRoot = root === value;
    const isNumberKey = Number.isInteger(Number(key));
    const storeEnableAdd = useJsonViewerStore((store)=>store.enableAdd);
    const onAdd = useJsonViewerStore((store)=>store.onAdd);
    const enableAdd = (0,react.useMemo)(()=>{
        if (!onAdd || nestedIndex !== undefined) return false;
        if (storeEnableAdd === false) {
            return false;
        }
        if (propsEditable === false) {
            // props.editable is false which means we cannot provide the suitable way to edit it
            return false;
        }
        if (typeof storeEnableAdd === 'function') {
            return !!storeEnableAdd(path, value);
        }
        if (Array.isArray(value) || isPlainObject(value)) {
            return true;
        }
        return false;
    }, [
        onAdd,
        nestedIndex,
        path,
        storeEnableAdd,
        propsEditable,
        value
    ]);
    const storeEnableDelete = useJsonViewerStore((store)=>store.enableDelete);
    const onDelete = useJsonViewerStore((store)=>store.onDelete);
    const enableDelete = (0,react.useMemo)(()=>{
        if (!onDelete || nestedIndex !== undefined) return false;
        if (isRoot) {
            // don't allow delete root
            return false;
        }
        if (storeEnableDelete === false) {
            return false;
        }
        if (propsEditable === false) {
            // props.editable is false which means we cannot provide the suitable way to edit it
            return false;
        }
        if (typeof storeEnableDelete === 'function') {
            return !!storeEnableDelete(path, value);
        }
        return storeEnableDelete;
    }, [
        onDelete,
        nestedIndex,
        isRoot,
        path,
        storeEnableDelete,
        propsEditable,
        value
    ]);
    const enableClipboard = useJsonViewerStore((store)=>store.enableClipboard);
    const { copy, copied } = useClipboard();
    const highlightUpdates = useJsonViewerStore((store)=>store.highlightUpdates);
    const isHighlight = (0,react.useMemo)(()=>{
        if (!highlightUpdates || prevValue === undefined) return false;
        // highlight if value type changed
        if (typeof value !== typeof prevValue) {
            return true;
        }
        if (typeof value === 'number') {
            // notice: NaN !== NaN
            if (isNaN(value) && isNaN(prevValue)) return false;
            return value !== prevValue;
        }
        // highlight if isArray changed
        if (Array.isArray(value) !== Array.isArray(prevValue)) {
            return true;
        }
        // not highlight object/function
        // deep compare they will be slow
        if (typeof value === 'object' || typeof value === 'function') {
            return false;
        }
        // highlight if not equal
        if (value !== prevValue) {
            return true;
        }
        return false;
    }, [
        highlightUpdates,
        prevValue,
        value
    ]);
    const highlightContainer = (0,react.useRef)();
    (0,react.useEffect)(()=>{
        if (highlightContainer.current && isHighlight && 'animate' in highlightContainer.current) {
            highlightContainer.current.animate([
                {
                    backgroundColor: highlightColor
                },
                {
                    backgroundColor: ''
                }
            ], {
                duration: 1000,
                easing: 'ease-in'
            });
        }
    }, [
        highlightColor,
        isHighlight,
        prevValue,
        value
    ]);
    const startEditing = (0,react.useCallback)((event)=>{
        event.preventDefault();
        if (serialize) setTempValue(serialize(value));
        setEditing(true);
    }, [
        serialize,
        value
    ]);
    const abortEditing = (0,react.useCallback)(()=>{
        setEditing(false);
        setTempValue('');
    }, [
        setEditing,
        setTempValue
    ]);
    const commitEditing = (0,react.useCallback)((newValue)=>{
        setEditing(false);
        if (!deserialize) return;
        try {
            onChange(path, value, deserialize(newValue));
        } catch (e) {
        // do nothing when deserialize failed
        }
    }, [
        setEditing,
        deserialize,
        onChange,
        path,
        value
    ]);
    const actionIcons = (0,react.useMemo)(()=>{
        if (editing) {
            return /*#__PURE__*/ (0,jsx_runtime.jsxs)(jsx_runtime.Fragment, {
                children: [
                    /*#__PURE__*/ (0,jsx_runtime.jsx)(IconBox, {
                        children: /*#__PURE__*/ (0,jsx_runtime.jsx)(CloseIcon, {
                            sx: {
                                fontSize: '.8rem'
                            },
                            onClick: abortEditing
                        })
                    }),
                    /*#__PURE__*/ (0,jsx_runtime.jsx)(IconBox, {
                        children: /*#__PURE__*/ (0,jsx_runtime.jsx)(CheckIcon, {
                            sx: {
                                fontSize: '.8rem'
                            },
                            onClick: ()=>commitEditing(tempValue)
                        })
                    })
                ]
            });
        }
        return /*#__PURE__*/ (0,jsx_runtime.jsxs)(jsx_runtime.Fragment, {
            children: [
                enableClipboard && /*#__PURE__*/ (0,jsx_runtime.jsx)(IconBox, {
                    onClick: (event)=>{
                        event.preventDefault();
                        try {
                            copy(path, value, copyString);
                        } catch (e) {
                            // in some case, this will throw error
                            // fixme: `useAlert` hook
                            console.error(e);
                        }
                    },
                    children: copied ? /*#__PURE__*/ (0,jsx_runtime.jsx)(CheckIcon, {
                        sx: {
                            fontSize: '.8rem'
                        }
                    }) : /*#__PURE__*/ (0,jsx_runtime.jsx)(ContentCopyIcon, {
                        sx: {
                            fontSize: '.8rem'
                        }
                    })
                }),
                Editor && editable && serialize && deserialize && /*#__PURE__*/ (0,jsx_runtime.jsx)(IconBox, {
                    onClick: startEditing,
                    children: /*#__PURE__*/ (0,jsx_runtime.jsx)(EditIcon, {
                        sx: {
                            fontSize: '.8rem'
                        }
                    })
                }),
                enableAdd && /*#__PURE__*/ (0,jsx_runtime.jsx)(IconBox, {
                    onClick: (event)=>{
                        event.preventDefault();
                        onAdd === null || onAdd === void 0 ? void 0 : onAdd(path);
                    },
                    children: /*#__PURE__*/ (0,jsx_runtime.jsx)(AddBoxIcon, {
                        sx: {
                            fontSize: '.8rem'
                        }
                    })
                }),
                enableDelete && /*#__PURE__*/ (0,jsx_runtime.jsx)(IconBox, {
                    onClick: (event)=>{
                        event.preventDefault();
                        onDelete === null || onDelete === void 0 ? void 0 : onDelete(path, value);
                    },
                    children: /*#__PURE__*/ (0,jsx_runtime.jsx)(DeleteIcon, {
                        sx: {
                            fontSize: '.9rem'
                        }
                    })
                })
            ]
        });
    }, [
        Editor,
        serialize,
        deserialize,
        copied,
        copy,
        editable,
        editing,
        enableClipboard,
        enableAdd,
        enableDelete,
        tempValue,
        path,
        value,
        onAdd,
        onDelete,
        startEditing,
        abortEditing,
        commitEditing
    ]);
    const isEmptyValue = (0,react.useMemo)(()=>getValueSize(value) === 0, [
        value
    ]);
    const expandable = !isEmptyValue && !!(PreComponent && PostComponent);
    const KeyRenderer = useJsonViewerStore((store)=>store.keyRenderer);
    const downstreamProps = (0,react.useMemo)(()=>({
            path,
            inspect,
            setInspect,
            value,
            prevValue,
            nestedIndex
        }), [
        inspect,
        path,
        setInspect,
        value,
        prevValue,
        nestedIndex
    ]);
    return /*#__PURE__*/ (0,jsx_runtime.jsxs)(Box/* default */.A, {
        className: "data-key-pair",
        "data-testid": 'data-key-pair' + path.join('.'),
        sx: {
            userSelect: 'text'
        },
        onMouseEnter: (0,react.useCallback)(()=>setHover(path, nestedIndex), [
            setHover,
            path,
            nestedIndex
        ]),
        children: [
            /*#__PURE__*/ (0,jsx_runtime.jsxs)(DataBox, {
                component: "span",
                className: "data-key",
                sx: {
                    lineHeight: 1.5,
                    color: keyColor,
                    letterSpacing: 0.5,
                    opacity: 0.8
                },
                onClick: (0,react.useCallback)((event)=>{
                    if (event.isDefaultPrevented()) {
                        return;
                    }
                    if (!isEmptyValue) {
                        setInspect((state)=>!state);
                    }
                }, [
                    isEmptyValue,
                    setInspect
                ]),
                children: [
                    expandable ? inspect ? /*#__PURE__*/ (0,jsx_runtime.jsx)(ExpandMoreIcon, {
                        className: "data-key-toggle-expanded",
                        sx: {
                            fontSize: '.8rem',
                            '&:hover': {
                                cursor: 'pointer'
                            }
                        }
                    }) : /*#__PURE__*/ (0,jsx_runtime.jsx)(ChevronRightIcon, {
                        className: "data-key-toggle-collapsed",
                        sx: {
                            fontSize: '.8rem',
                            '&:hover': {
                                cursor: 'pointer'
                            }
                        }
                    }) : null,
                    /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                        ref: highlightContainer,
                        className: "data-key-key",
                        component: "span",
                        children: isRoot && depth === 0 ? rootName !== false ? quotesOnKeys ? /*#__PURE__*/ (0,jsx_runtime.jsxs)(jsx_runtime.Fragment, {
                            children: [
                                '"',
                                rootName,
                                '"'
                            ]
                        }) : /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
                            children: rootName
                        }) : null : KeyRenderer.when(downstreamProps) ? /*#__PURE__*/ (0,jsx_runtime.jsx)(KeyRenderer, {
                            ...downstreamProps
                        }) : nestedIndex === undefined && (isNumberKey ? /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                            component: "span",
                            style: {
                                color: numberKeyColor,
                                userSelect: isNumberKey ? 'none' : 'auto'
                            },
                            children: key
                        }) : quotesOnKeys ? /*#__PURE__*/ (0,jsx_runtime.jsxs)(jsx_runtime.Fragment, {
                            children: [
                                '"',
                                key,
                                '"'
                            ]
                        }) : /*#__PURE__*/ (0,jsx_runtime.jsx)(jsx_runtime.Fragment, {
                            children: key
                        }))
                    }),
                    isRoot ? rootName !== false && /*#__PURE__*/ (0,jsx_runtime.jsx)(DataBox, {
                        className: "data-key-colon",
                        sx: {
                            mr: 0.5
                        },
                        children: ":"
                    }) : nestedIndex === undefined && /*#__PURE__*/ (0,jsx_runtime.jsx)(DataBox, {
                        className: "data-key-colon",
                        sx: {
                            mr: 0.5,
                            '.data-key-key:empty + &': {
                                display: 'none'
                            },
                            userSelect: isNumberKey ? 'none' : 'auto'
                        },
                        children: ":"
                    }),
                    PreComponent && /*#__PURE__*/ (0,jsx_runtime.jsx)(PreComponent, {
                        ...downstreamProps
                    }),
                    isHover && expandable && inspect && actionIcons
                ]
            }),
            editing && editable ? Editor && /*#__PURE__*/ (0,jsx_runtime.jsx)(Editor, {
                path: path,
                value: tempValue,
                setValue: setTempValue,
                abortEditing: abortEditing,
                commitEditing: commitEditing
            }) : Component ? /*#__PURE__*/ (0,jsx_runtime.jsx)(Component, {
                ...downstreamProps
            }) : /*#__PURE__*/ (0,jsx_runtime.jsx)(Box/* default */.A, {
                component: "span",
                className: "data-value-fallback",
                children: "fallback: ".concat(value)
            }),
            PostComponent && /*#__PURE__*/ (0,jsx_runtime.jsx)(PostComponent, {
                ...downstreamProps
            }),
            !last && displayComma && /*#__PURE__*/ (0,jsx_runtime.jsx)(DataBox, {
                children: ","
            }),
            isHover && expandable && !inspect && actionIcons,
            isHover && !expandable && actionIcons,
            !isHover && editing && actionIcons
        ]
    });
};

const query = '(prefers-color-scheme: dark)';
function useThemeDetector() {
    const [isDark, setIsDark] = (0,react.useState)(false);
    (0,react.useEffect)(()=>{
        const listener = (e)=>setIsDark(e.matches);
        setIsDark(window.matchMedia(query).matches);
        const queryMedia = window.matchMedia(query);
        queryMedia.addEventListener('change', listener);
        return ()=>queryMedia.removeEventListener('change', listener);
    }, []);
    return isDark;
}

/**
 * @internal
 */ function useSetIfNotUndefinedEffect(key, value) {
    const { setState } = (0,react.useContext)(JsonViewerStoreContext);
    (0,react.useEffect)(()=>{
        if (value !== undefined) {
            setState({
                [key]: value
            });
        }
    }, [
        key,
        value,
        setState
    ]);
}
/**
 * @internal
 */ const JsonViewerInner = (props)=>{
    const { setState } = (0,react.useContext)(JsonViewerStoreContext);
    (0,react.useEffect)(()=>{
        setState((state)=>({
                prevValue: state.value,
                value: props.value
            }));
    }, [
        props.value,
        setState
    ]);
    useSetIfNotUndefinedEffect('rootName', props.rootName);
    useSetIfNotUndefinedEffect('indentWidth', props.indentWidth);
    useSetIfNotUndefinedEffect('keyRenderer', props.keyRenderer);
    useSetIfNotUndefinedEffect('enableAdd', props.enableAdd);
    useSetIfNotUndefinedEffect('enableDelete', props.enableDelete);
    useSetIfNotUndefinedEffect('enableClipboard', props.enableClipboard);
    useSetIfNotUndefinedEffect('editable', props.editable);
    useSetIfNotUndefinedEffect('onChange', props.onChange);
    useSetIfNotUndefinedEffect('onCopy', props.onCopy);
    useSetIfNotUndefinedEffect('onSelect', props.onSelect);
    useSetIfNotUndefinedEffect('onAdd', props.onAdd);
    useSetIfNotUndefinedEffect('onDelete', props.onDelete);
    useSetIfNotUndefinedEffect('maxDisplayLength', props.maxDisplayLength);
    useSetIfNotUndefinedEffect('groupArraysAfterLength', props.groupArraysAfterLength);
    useSetIfNotUndefinedEffect('quotesOnKeys', props.quotesOnKeys);
    useSetIfNotUndefinedEffect('displayDataTypes', props.displayDataTypes);
    useSetIfNotUndefinedEffect('displaySize', props.displaySize);
    useSetIfNotUndefinedEffect('displayComma', props.displayComma);
    useSetIfNotUndefinedEffect('highlightUpdates', props.highlightUpdates);
    (0,react.useEffect)(()=>{
        if (props.theme === 'light') {
            setState({
                colorspace: lightColorspace
            });
        } else if (props.theme === 'dark') {
            setState({
                colorspace: darkColorspace
            });
        } else if (typeof props.theme === 'object') {
            setState({
                colorspace: props.theme
            });
        }
    }, [
        setState,
        props.theme
    ]);
    const themeCls = (0,react.useMemo)(()=>{
        if (typeof props.theme === 'object') return 'json-viewer-theme-custom';
        return props.theme === 'dark' ? 'json-viewer-theme-dark' : 'json-viewer-theme-light';
    }, [
        props.theme
    ]);
    const onceRef = (0,react.useRef)(true);
    const registerTypes = useTypeRegistryStore((store)=>store.registerTypes);
    if (onceRef.current) {
        const allTypes = props.valueTypes ? [
            ...predefinedTypes,
            ...props.valueTypes
        ] : [
            ...predefinedTypes
        ];
        registerTypes(allTypes);
        onceRef.current = false;
    }
    (0,react.useEffect)(()=>{
        const allTypes = props.valueTypes ? [
            ...predefinedTypes,
            ...props.valueTypes
        ] : [
            ...predefinedTypes
        ];
        registerTypes(allTypes);
    }, [
        props.valueTypes,
        registerTypes
    ]);
    const value = useJsonViewerStore((store)=>store.value);
    const prevValue = useJsonViewerStore((store)=>store.prevValue);
    const emptyPath = (0,react.useMemo)(()=>[], []);
    const setHover = useJsonViewerStore((store)=>store.setHover);
    const onMouseLeave = (0,react.useCallback)(()=>setHover(null), [
        setHover
    ]);
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(Paper/* default */.A, {
        elevation: 0,
        className: clsx(themeCls, props.className),
        style: props.style,
        sx: {
            fontFamily: 'monospace',
            userSelect: 'none',
            contentVisibility: 'auto',
            ...props.sx
        },
        onMouseLeave: onMouseLeave,
        children: /*#__PURE__*/ (0,jsx_runtime.jsx)(DataKeyPair, {
            value: value,
            prevValue: prevValue,
            path: emptyPath,
            last: true
        })
    });
};
const JsonViewer = function JsonViewer(props) {
    if (false) // removed by dead control flow
{}
    const isAutoDarkTheme = useThemeDetector();
    const themeType = (0,react.useMemo)(()=>{
        var _props_theme;
        return props.theme === 'auto' ? isAutoDarkTheme ? 'dark' : 'light' : (_props_theme = props.theme) !== null && _props_theme !== void 0 ? _props_theme : 'light';
    }, [
        isAutoDarkTheme,
        props.theme
    ]);
    const theme = (0,react.useMemo)(()=>{
        const backgroundColor = typeof themeType === 'object' ? themeType.base00 : themeType === 'dark' ? darkColorspace.base00 : lightColorspace.base00;
        const foregroundColor = typeof themeType === 'object' ? themeType.base07 : themeType === 'dark' ? darkColorspace.base07 : lightColorspace.base07;
        return (0,createTheme/* default */.A)({
            components: {
                MuiPaper: {
                    styleOverrides: {
                        root: {
                            backgroundColor,
                            color: foregroundColor
                        }
                    }
                }
            },
            palette: {
                mode: themeType === 'dark' ? 'dark' : 'light',
                background: {
                    default: backgroundColor
                }
            }
        });
    }, [
        themeType
    ]);
    const mixedProps = {
        ...props,
        theme: themeType
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const jsonViewerStore = (0,react.useMemo)(()=>createJsonViewerStore(props), []);
    const typeRegistryStore = (0,react.useMemo)(()=>createTypeRegistryStore(), []);
    return /*#__PURE__*/ (0,jsx_runtime.jsx)(ThemeProvider/* default */.A, {
        theme: theme,
        children: /*#__PURE__*/ (0,jsx_runtime.jsx)(TypeRegistryStoreContext.Provider, {
            value: typeRegistryStore,
            children: /*#__PURE__*/ (0,jsx_runtime.jsx)(JsonViewerStoreContext.Provider, {
                value: jsonViewerStore,
                children: /*#__PURE__*/ (0,jsx_runtime.jsx)(JsonViewerInner, {
                    ...mixedProps
                })
            })
        })
    });
};




/***/ }),

/***/ 3948:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=IJsonModel.js.map

/***/ }),

/***/ 4017:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DropInfo = void 0;
class DropInfo {
    constructor(node, rect, location, index, className) {
        this.node = node;
        this.rect = rect;
        this.location = location;
        this.index = index;
        this.className = className;
    }
}
exports.DropInfo = DropInfo;
//# sourceMappingURL=DropInfo.js.map

/***/ }),

/***/ 4038:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  A: function() { return /* binding */ esm_TransitionGroup; }
});

// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
var objectWithoutPropertiesLoose = __webpack_require__(8587);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__(8168);
;// ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
function _assertThisInitialized(e) {
  if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  return e;
}

// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js + 1 modules
var inheritsLoose = __webpack_require__(5540);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(6540);
// EXTERNAL MODULE: ./node_modules/react-transition-group/esm/TransitionGroupContext.js
var TransitionGroupContext = __webpack_require__(7241);
;// ./node_modules/react-transition-group/esm/utils/ChildMapping.js

/**
 * Given `this.props.children`, return an object mapping key to child.
 *
 * @param {*} children `this.props.children`
 * @return {object} Mapping of key to child
 */

function getChildMapping(children, mapFn) {
  var mapper = function mapper(child) {
    return mapFn && (0,react.isValidElement)(child) ? mapFn(child) : child;
  };

  var result = Object.create(null);
  if (children) react.Children.map(children, function (c) {
    return c;
  }).forEach(function (child) {
    // run the map function here instead so that the key is the computed one
    result[child.key] = mapper(child);
  });
  return result;
}
/**
 * When you're adding or removing children some may be added or removed in the
 * same render pass. We want to show *both* since we want to simultaneously
 * animate elements in and out. This function takes a previous set of keys
 * and a new set of keys and merges them with its best guess of the correct
 * ordering. In the future we may expose some of the utilities in
 * ReactMultiChild to make this easy, but for now React itself does not
 * directly have this concept of the union of prevChildren and nextChildren
 * so we implement it here.
 *
 * @param {object} prev prev children as returned from
 * `ReactTransitionChildMapping.getChildMapping()`.
 * @param {object} next next children as returned from
 * `ReactTransitionChildMapping.getChildMapping()`.
 * @return {object} a key set that contains all keys in `prev` and all keys
 * in `next` in a reasonable order.
 */

function mergeChildMappings(prev, next) {
  prev = prev || {};
  next = next || {};

  function getValueForKey(key) {
    return key in next ? next[key] : prev[key];
  } // For each key of `next`, the list of keys to insert before that key in
  // the combined list


  var nextKeysPending = Object.create(null);
  var pendingKeys = [];

  for (var prevKey in prev) {
    if (prevKey in next) {
      if (pendingKeys.length) {
        nextKeysPending[prevKey] = pendingKeys;
        pendingKeys = [];
      }
    } else {
      pendingKeys.push(prevKey);
    }
  }

  var i;
  var childMapping = {};

  for (var nextKey in next) {
    if (nextKeysPending[nextKey]) {
      for (i = 0; i < nextKeysPending[nextKey].length; i++) {
        var pendingNextKey = nextKeysPending[nextKey][i];
        childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
      }
    }

    childMapping[nextKey] = getValueForKey(nextKey);
  } // Finally, add the keys which didn't appear before any key in `next`


  for (i = 0; i < pendingKeys.length; i++) {
    childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
  }

  return childMapping;
}

function getProp(child, prop, props) {
  return props[prop] != null ? props[prop] : child.props[prop];
}

function getInitialChildMapping(props, onExited) {
  return getChildMapping(props.children, function (child) {
    return (0,react.cloneElement)(child, {
      onExited: onExited.bind(null, child),
      in: true,
      appear: getProp(child, 'appear', props),
      enter: getProp(child, 'enter', props),
      exit: getProp(child, 'exit', props)
    });
  });
}
function getNextChildMapping(nextProps, prevChildMapping, onExited) {
  var nextChildMapping = getChildMapping(nextProps.children);
  var children = mergeChildMappings(prevChildMapping, nextChildMapping);
  Object.keys(children).forEach(function (key) {
    var child = children[key];
    if (!(0,react.isValidElement)(child)) return;
    var hasPrev = (key in prevChildMapping);
    var hasNext = (key in nextChildMapping);
    var prevChild = prevChildMapping[key];
    var isLeaving = (0,react.isValidElement)(prevChild) && !prevChild.props.in; // item is new (entering)

    if (hasNext && (!hasPrev || isLeaving)) {
      // console.log('entering', key)
      children[key] = (0,react.cloneElement)(child, {
        onExited: onExited.bind(null, child),
        in: true,
        exit: getProp(child, 'exit', nextProps),
        enter: getProp(child, 'enter', nextProps)
      });
    } else if (!hasNext && hasPrev && !isLeaving) {
      // item is old (exiting)
      // console.log('leaving', key)
      children[key] = (0,react.cloneElement)(child, {
        in: false
      });
    } else if (hasNext && hasPrev && (0,react.isValidElement)(prevChild)) {
      // item hasn't changed transition states
      // copy over the last transition props;
      // console.log('unchanged', key)
      children[key] = (0,react.cloneElement)(child, {
        onExited: onExited.bind(null, child),
        in: prevChild.props.in,
        exit: getProp(child, 'exit', nextProps),
        enter: getProp(child, 'enter', nextProps)
      });
    }
  });
  return children;
}
;// ./node_modules/react-transition-group/esm/TransitionGroup.js









var values = Object.values || function (obj) {
  return Object.keys(obj).map(function (k) {
    return obj[k];
  });
};

var defaultProps = {
  component: 'div',
  childFactory: function childFactory(child) {
    return child;
  }
};
/**
 * The `<TransitionGroup>` component manages a set of transition components
 * (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition
 * components, `<TransitionGroup>` is a state machine for managing the mounting
 * and unmounting of components over time.
 *
 * Consider the example below. As items are removed or added to the TodoList the
 * `in` prop is toggled automatically by the `<TransitionGroup>`.
 *
 * Note that `<TransitionGroup>`  does not define any animation behavior!
 * Exactly _how_ a list item animates is up to the individual transition
 * component. This means you can mix and match animations across different list
 * items.
 */

var TransitionGroup = /*#__PURE__*/function (_React$Component) {
  (0,inheritsLoose/* default */.A)(TransitionGroup, _React$Component);

  function TransitionGroup(props, context) {
    var _this;

    _this = _React$Component.call(this, props, context) || this;

    var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear


    _this.state = {
      contextValue: {
        isMounting: true
      },
      handleExited: handleExited,
      firstRender: true
    };
    return _this;
  }

  var _proto = TransitionGroup.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.mounted = true;
    this.setState({
      contextValue: {
        isMounting: false
      }
    });
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    this.mounted = false;
  };

  TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {
    var prevChildMapping = _ref.children,
        handleExited = _ref.handleExited,
        firstRender = _ref.firstRender;
    return {
      children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),
      firstRender: false
    };
  } // node is `undefined` when user provided `nodeRef` prop
  ;

  _proto.handleExited = function handleExited(child, node) {
    var currentChildMapping = getChildMapping(this.props.children);
    if (child.key in currentChildMapping) return;

    if (child.props.onExited) {
      child.props.onExited(node);
    }

    if (this.mounted) {
      this.setState(function (state) {
        var children = (0,esm_extends/* default */.A)({}, state.children);

        delete children[child.key];
        return {
          children: children
        };
      });
    }
  };

  _proto.render = function render() {
    var _this$props = this.props,
        Component = _this$props.component,
        childFactory = _this$props.childFactory,
        props = (0,objectWithoutPropertiesLoose/* default */.A)(_this$props, ["component", "childFactory"]);

    var contextValue = this.state.contextValue;
    var children = values(this.state.children).map(childFactory);
    delete props.appear;
    delete props.enter;
    delete props.exit;

    if (Component === null) {
      return /*#__PURE__*/react.createElement(TransitionGroupContext/* default */.A.Provider, {
        value: contextValue
      }, children);
    }

    return /*#__PURE__*/react.createElement(TransitionGroupContext/* default */.A.Provider, {
      value: contextValue
    }, /*#__PURE__*/react.createElement(Component, props, children));
  };

  return TransitionGroup;
}(react.Component);

TransitionGroup.propTypes =  false ? 0 : {};
TransitionGroup.defaultProps = defaultProps;
/* harmony default export */ var esm_TransitionGroup = (TransitionGroup);

/***/ }),

/***/ 4146:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";


var reactIs = __webpack_require__(3404);

/**
 * Copyright 2015, Yahoo! Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
var REACT_STATICS = {
  childContextTypes: true,
  contextType: true,
  contextTypes: true,
  defaultProps: true,
  displayName: true,
  getDefaultProps: true,
  getDerivedStateFromError: true,
  getDerivedStateFromProps: true,
  mixins: true,
  propTypes: true,
  type: true
};
var KNOWN_STATICS = {
  name: true,
  length: true,
  prototype: true,
  caller: true,
  callee: true,
  arguments: true,
  arity: true
};
var FORWARD_REF_STATICS = {
  '$$typeof': true,
  render: true,
  defaultProps: true,
  displayName: true,
  propTypes: true
};
var MEMO_STATICS = {
  '$$typeof': true,
  compare: true,
  defaultProps: true,
  displayName: true,
  propTypes: true,
  type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;

function getStatics(component) {
  // React v16.11 and below
  if (reactIs.isMemo(component)) {
    return MEMO_STATICS;
  } // React v16.12 and above


  return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}

var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
  if (typeof sourceComponent !== 'string') {
    // don't hoist over string (html) components
    if (objectPrototype) {
      var inheritedComponent = getPrototypeOf(sourceComponent);

      if (inheritedComponent && inheritedComponent !== objectPrototype) {
        hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
      }
    }

    var keys = getOwnPropertyNames(sourceComponent);

    if (getOwnPropertySymbols) {
      keys = keys.concat(getOwnPropertySymbols(sourceComponent));
    }

    var targetStatics = getStatics(targetComponent);
    var sourceStatics = getStatics(sourceComponent);

    for (var i = 0; i < keys.length; ++i) {
      var key = keys[i];

      if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
        var descriptor = getOwnPropertyDescriptor(sourceComponent, key);

        try {
          // Avoid failures from read-only properties
          defineProperty(targetComponent, key, descriptor);
        } catch (e) {}
      }
    }
  }

  return targetComponent;
}

module.exports = hoistNonReactStatics;


/***/ }),

/***/ 4164:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export clsx */
function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f)}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}/* harmony default export */ __webpack_exports__.A = (clsx);

/***/ }),

/***/ 4405:
/***/ (function(__unused_webpack_module, exports) {

"use strict";
var __webpack_unused_export__;
/**
 * @license React
 * react-is.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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 = Symbol.for("react.transitional.element"),
  REACT_PORTAL_TYPE = Symbol.for("react.portal"),
  REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
  REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
  REACT_PROFILER_TYPE = Symbol.for("react.profiler");
Symbol.for("react.provider");
var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
  REACT_CONTEXT_TYPE = Symbol.for("react.context"),
  REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
  REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
  REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"),
  REACT_MEMO_TYPE = Symbol.for("react.memo"),
  REACT_LAZY_TYPE = Symbol.for("react.lazy"),
  REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"),
  REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference");
function typeOf(object) {
  if ("object" === typeof object && null !== object) {
    var $$typeof = object.$$typeof;
    switch ($$typeof) {
      case REACT_ELEMENT_TYPE:
        switch (((object = object.type), object)) {
          case REACT_FRAGMENT_TYPE:
          case REACT_PROFILER_TYPE:
          case REACT_STRICT_MODE_TYPE:
          case REACT_SUSPENSE_TYPE:
          case REACT_SUSPENSE_LIST_TYPE:
          case REACT_VIEW_TRANSITION_TYPE:
            return object;
          default:
            switch (((object = object && object.$$typeof), object)) {
              case REACT_CONTEXT_TYPE:
              case REACT_FORWARD_REF_TYPE:
              case REACT_LAZY_TYPE:
              case REACT_MEMO_TYPE:
                return object;
              case REACT_CONSUMER_TYPE:
                return object;
              default:
                return $$typeof;
            }
        }
      case REACT_PORTAL_TYPE:
        return $$typeof;
    }
  }
}
__webpack_unused_export__ = REACT_CONSUMER_TYPE;
__webpack_unused_export__ = REACT_CONTEXT_TYPE;
__webpack_unused_export__ = REACT_ELEMENT_TYPE;
exports.vM = REACT_FORWARD_REF_TYPE;
__webpack_unused_export__ = REACT_FRAGMENT_TYPE;
__webpack_unused_export__ = REACT_LAZY_TYPE;
exports.lD = REACT_MEMO_TYPE;
__webpack_unused_export__ = REACT_PORTAL_TYPE;
__webpack_unused_export__ = REACT_PROFILER_TYPE;
__webpack_unused_export__ = REACT_STRICT_MODE_TYPE;
__webpack_unused_export__ = REACT_SUSPENSE_TYPE;
__webpack_unused_export__ = REACT_SUSPENSE_LIST_TYPE;
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_CONSUMER_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_CONTEXT_TYPE;
};
__webpack_unused_export__ = function (object) {
  return (
    "object" === typeof object &&
    null !== object &&
    object.$$typeof === REACT_ELEMENT_TYPE
  );
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_FORWARD_REF_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_FRAGMENT_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_LAZY_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_MEMO_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_PORTAL_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_PROFILER_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_STRICT_MODE_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_SUSPENSE_TYPE;
};
__webpack_unused_export__ = function (object) {
  return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
};
__webpack_unused_export__ = function (type) {
  return "string" === typeof type ||
    "function" === typeof type ||
    type === REACT_FRAGMENT_TYPE ||
    type === REACT_PROFILER_TYPE ||
    type === REACT_STRICT_MODE_TYPE ||
    type === REACT_SUSPENSE_TYPE ||
    type === REACT_SUSPENSE_LIST_TYPE ||
    ("object" === typeof type &&
      null !== type &&
      (type.$$typeof === REACT_LAZY_TYPE ||
        type.$$typeof === REACT_MEMO_TYPE ||
        type.$$typeof === REACT_CONTEXT_TYPE ||
        type.$$typeof === REACT_CONSUMER_TYPE ||
        type.$$typeof === REACT_FORWARD_REF_TYPE ||
        type.$$typeof === REACT_CLIENT_REFERENCE ||
        void 0 !== type.getModuleId))
    ? !0
    : !1;
};
__webpack_unused_export__ = typeOf;


/***/ }),

/***/ 4634:
/***/ (function(module) {

function _extends() {
  return module.exports = _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, module.exports.__esModule = true, module.exports["default"] = module.exports, _extends.apply(null, arguments);
}
module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 4684:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   C: function() { return /* binding */ CacheProvider; },
/* harmony export */   E: function() { return /* binding */ Emotion$1; },
/* harmony export */   T: function() { return /* binding */ ThemeContext; },
/* harmony export */   c: function() { return /* binding */ createEmotionProps; },
/* harmony export */   h: function() { return /* binding */ hasOwn; },
/* harmony export */   w: function() { return /* binding */ withEmotionCache; }
/* harmony export */ });
/* unused harmony exports _, a, b, i, u */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6540);
/* harmony import */ var _emotion_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5655);
/* harmony import */ var _emotion_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(41);
/* harmony import */ var _emotion_serialize__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3174);
/* harmony import */ var _emotion_use_insertion_effect_with_fallbacks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1287);










var isDevelopment = false;

var EmotionCacheContext = /* #__PURE__ */react__WEBPACK_IMPORTED_MODULE_0__.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
typeof HTMLElement !== 'undefined' ? /* #__PURE__ */(0,_emotion_cache__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)({
  key: 'css'
}) : null);

var CacheProvider = EmotionCacheContext.Provider;
var __unsafe_useEmotionCache = function useEmotionCache() {
  return useContext(EmotionCacheContext);
};

var withEmotionCache = function withEmotionCache(func) {
  return /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(function (props, ref) {
    // the cache will never be null in the browser
    var cache = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(EmotionCacheContext);
    return func(props, cache, ref);
  });
};

var ThemeContext = /* #__PURE__ */react__WEBPACK_IMPORTED_MODULE_0__.createContext({});

var useTheme = function useTheme() {
  return React.useContext(ThemeContext);
};

var getTheme = function getTheme(outerTheme, theme) {
  if (typeof theme === 'function') {
    var mergedTheme = theme(outerTheme);

    return mergedTheme;
  }

  return _extends({}, outerTheme, theme);
};

var createCacheWithTheme = /* #__PURE__ */(/* unused pure expression or super */ null && (weakMemoize(function (outerTheme) {
  return weakMemoize(function (theme) {
    return getTheme(outerTheme, theme);
  });
})));
var ThemeProvider = function ThemeProvider(props) {
  var theme = React.useContext(ThemeContext);

  if (props.theme !== theme) {
    theme = createCacheWithTheme(theme)(props.theme);
  }

  return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
    value: theme
  }, props.children);
};
function withTheme(Component) {
  var componentName = Component.displayName || Component.name || 'Component';
  var WithTheme = /*#__PURE__*/React.forwardRef(function render(props, ref) {
    var theme = React.useContext(ThemeContext);
    return /*#__PURE__*/React.createElement(Component, _extends({
      theme: theme,
      ref: ref
    }, props));
  });
  WithTheme.displayName = "WithTheme(" + componentName + ")";
  return hoistNonReactStatics(WithTheme, Component);
}

var hasOwn = {}.hasOwnProperty;

var typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';
var createEmotionProps = function createEmotionProps(type, props) {

  var newProps = {};

  for (var _key in props) {
    if (hasOwn.call(props, _key)) {
      newProps[_key] = props[_key];
    }
  }

  newProps[typePropName] = type; // Runtime labeling is an opt-in feature because:

  return newProps;
};

var Insertion = function Insertion(_ref) {
  var cache = _ref.cache,
      serialized = _ref.serialized,
      isStringTag = _ref.isStringTag;
  (0,_emotion_utils__WEBPACK_IMPORTED_MODULE_2__/* .registerStyles */ .SF)(cache, serialized, isStringTag);
  (0,_emotion_use_insertion_effect_with_fallbacks__WEBPACK_IMPORTED_MODULE_4__/* .useInsertionEffectAlwaysWithSyncFallback */ .s)(function () {
    return (0,_emotion_utils__WEBPACK_IMPORTED_MODULE_2__/* .insertStyles */ .sk)(cache, serialized, isStringTag);
  });

  return null;
};

var Emotion = /* #__PURE__ */withEmotionCache(function (props, cache, ref) {
  var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works
  // not passing the registered cache to serializeStyles because it would
  // make certain babel optimisations not possible

  if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {
    cssProp = cache.registered[cssProp];
  }

  var WrappedComponent = props[typePropName];
  var registeredStyles = [cssProp];
  var className = '';

  if (typeof props.className === 'string') {
    className = (0,_emotion_utils__WEBPACK_IMPORTED_MODULE_2__/* .getRegisteredStyles */ .Rk)(cache.registered, registeredStyles, props.className);
  } else if (props.className != null) {
    className = props.className + " ";
  }

  var serialized = (0,_emotion_serialize__WEBPACK_IMPORTED_MODULE_3__/* .serializeStyles */ .J)(registeredStyles, undefined, react__WEBPACK_IMPORTED_MODULE_0__.useContext(ThemeContext));

  className += cache.key + "-" + serialized.name;
  var newProps = {};

  for (var _key2 in props) {
    if (hasOwn.call(props, _key2) && _key2 !== 'css' && _key2 !== typePropName && (!isDevelopment )) {
      newProps[_key2] = props[_key2];
    }
  }

  newProps.className = className;

  if (ref) {
    newProps.ref = ref;
  }

  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(Insertion, {
    cache: cache,
    serialized: serialized,
    isStringTag: typeof WrappedComponent === 'string'
  }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(WrappedComponent, newProps));
});

var Emotion$1 = Emotion;




/***/ }),

/***/ 4767:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BorderTabSet = void 0;
const React = __webpack_require__(6540);
const DockLocation_1 = __webpack_require__(8324);
const BorderButton_1 = __webpack_require__(5742);
const PopupMenu_1 = __webpack_require__(9919);
const Actions_1 = __webpack_require__(9103);
const I18nLabel_1 = __webpack_require__(300);
const TabOverflowHook_1 = __webpack_require__(2272);
const Orientation_1 = __webpack_require__(1648);
const Types_1 = __webpack_require__(6643);
const Utils_1 = __webpack_require__(343);
/** @internal */
const BorderTabSet = (props) => {
    const { border, layout, iconFactory, titleFactory, icons, path } = props;
    const toolbarRef = React.useRef(null);
    const overflowbuttonRef = React.useRef(null);
    const stickyButtonsRef = React.useRef(null);
    const { selfRef, position, userControlledLeft, hiddenTabs, onMouseWheel, tabsTruncated } = (0, TabOverflowHook_1.useTabOverflow)(border, Orientation_1.Orientation.flip(border.getOrientation()), toolbarRef, stickyButtonsRef);
    const onAuxMouseClick = (event) => {
        if ((0, Utils_1.isAuxMouseEvent)(event)) {
            layout.auxMouseClick(border, event);
        }
    };
    const onContextMenu = (event) => {
        layout.showContextMenu(border, event);
    };
    const onInterceptMouseDown = (event) => {
        event.stopPropagation();
    };
    const onOverflowClick = (event) => {
        const callback = layout.getShowOverflowMenu();
        if (callback !== undefined) {
            callback(border, event, hiddenTabs, onOverflowItemSelect);
        }
        else {
            const element = overflowbuttonRef.current;
            (0, PopupMenu_1.showPopup)(element, hiddenTabs, onOverflowItemSelect, layout, iconFactory, titleFactory);
        }
        event.stopPropagation();
    };
    const onOverflowItemSelect = (item) => {
        layout.doAction(Actions_1.Actions.selectTab(item.node.getId()));
        userControlledLeft.current = false;
    };
    const onFloatTab = (event) => {
        const selectedTabNode = border.getChildren()[border.getSelected()];
        if (selectedTabNode !== undefined) {
            layout.doAction(Actions_1.Actions.floatTab(selectedTabNode.getId()));
        }
        event.stopPropagation();
    };
    const cm = layout.getClassName;
    let style = border.getTabHeaderRect().styleWithPosition({});
    const tabs = [];
    const layoutTab = (i) => {
        let isSelected = border.getSelected() === i;
        let child = border.getChildren()[i];
        tabs.push(React.createElement(BorderButton_1.BorderButton, { layout: layout, border: border.getLocation().getName(), node: child, path: path + "/tb" + i, key: child.getId(), selected: isSelected, iconFactory: iconFactory, titleFactory: titleFactory, icons: icons }));
        if (i < border.getChildren().length - 1) {
            tabs.push(React.createElement("div", { key: "divider" + i, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TAB_DIVIDER) }));
        }
    };
    for (let i = 0; i < border.getChildren().length; i++) {
        layoutTab(i);
    }
    let borderClasses = cm(Types_1.CLASSES.FLEXLAYOUT__BORDER) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_ + border.getLocation().getName());
    if (border.getClassName() !== undefined) {
        borderClasses += " " + border.getClassName();
    }
    // allow customization of tabset right/bottom buttons
    let buttons = [];
    let stickyButtons = [];
    const renderState = { headerContent: undefined, buttons, stickyButtons: stickyButtons, headerButtons: [], overflowPosition: undefined };
    layout.customizeTabSet(border, renderState);
    buttons = renderState.buttons;
    if (renderState.overflowPosition === undefined) {
        renderState.overflowPosition = stickyButtons.length;
    }
    if (stickyButtons.length > 0) {
        if (tabsTruncated) {
            buttons = [...stickyButtons, ...buttons];
        }
        else {
            tabs.push(React.createElement("div", { ref: stickyButtonsRef, key: "sticky_buttons_container", onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown, onDragStart: (e) => { e.preventDefault(); }, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER) }, stickyButtons));
        }
    }
    if (hiddenTabs.length > 0) {
        const overflowTitle = layout.i18nName(I18nLabel_1.I18nLabel.Overflow_Menu_Tooltip);
        let overflowContent;
        if (typeof icons.more === "function") {
            overflowContent = icons.more(border, hiddenTabs);
        }
        else {
            overflowContent = (React.createElement(React.Fragment, null,
                icons.more,
                React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT) }, hiddenTabs.length)));
        }
        buttons.splice(Math.min(renderState.overflowPosition, buttons.length), 0, React.createElement("button", { key: "overflowbutton", ref: overflowbuttonRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW_ + border.getLocation().getName()), title: overflowTitle, onClick: onOverflowClick, onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown }, overflowContent));
    }
    const selectedIndex = border.getSelected();
    if (selectedIndex !== -1) {
        const selectedTabNode = border.getChildren()[selectedIndex];
        if (selectedTabNode !== undefined && layout.isSupportsPopout() && selectedTabNode.isEnableFloat() && !selectedTabNode.isFloating()) {
            const floatTitle = layout.i18nName(I18nLabel_1.I18nLabel.Float_Tab);
            buttons.push(React.createElement("button", { key: "float", title: floatTitle, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_FLOAT), onClick: onFloatTab, onMouseDown: onInterceptMouseDown, onTouchStart: onInterceptMouseDown }, (typeof icons.popout === "function") ? icons.popout(selectedTabNode) : icons.popout));
        }
    }
    const toolbar = (React.createElement("div", { key: "toolbar", ref: toolbarRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_ + border.getLocation().getName()) }, buttons));
    style = layout.styleFont(style);
    let innerStyle = {};
    const borderHeight = border.getBorderBarSize() - 1;
    if (border.getLocation() === DockLocation_1.DockLocation.LEFT) {
        innerStyle = { right: borderHeight, height: borderHeight, top: position };
    }
    else if (border.getLocation() === DockLocation_1.DockLocation.RIGHT) {
        innerStyle = { left: borderHeight, height: borderHeight, top: position };
    }
    else {
        innerStyle = { height: borderHeight, left: position };
    }
    return (React.createElement("div", { ref: selfRef, dir: "ltr", style: style, className: borderClasses, "data-layout-path": path, onClick: onAuxMouseClick, onAuxClick: onAuxMouseClick, onContextMenu: onContextMenu, onWheel: onMouseWheel },
        React.createElement("div", { style: { height: borderHeight }, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_INNER) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_INNER_ + border.getLocation().getName()) },
            React.createElement("div", { style: innerStyle, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER_ + border.getLocation().getName()) }, tabs)),
        toolbar));
};
exports.BorderTabSet = BorderTabSet;
//# sourceMappingURL=BorderTabSet.js.map

/***/ }),

/***/ 4893:
/***/ (function(module) {

function _objectWithoutPropertiesLoose(r, e) {
  if (null == r) return {};
  var t = {};
  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
    if (-1 !== e.indexOf(n)) continue;
    t[n] = r[n];
  }
  return t;
}
module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 4948:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RowNode = void 0;
const Attribute_1 = __webpack_require__(46);
const AttributeDefinitions_1 = __webpack_require__(6874);
const DockLocation_1 = __webpack_require__(8324);
const DropInfo_1 = __webpack_require__(4017);
const Orientation_1 = __webpack_require__(1648);
const Rect_1 = __webpack_require__(2530);
const Types_1 = __webpack_require__(6643);
const BorderNode_1 = __webpack_require__(1480);
const Node_1 = __webpack_require__(7618);
const SplitterNode_1 = __webpack_require__(6169);
const TabSetNode_1 = __webpack_require__(9555);
class RowNode extends Node_1.Node {
    /** @internal */
    static _fromJson(json, model) {
        const newLayoutNode = new RowNode(model, json);
        if (json.children != null) {
            for (const jsonChild of json.children) {
                if (jsonChild.type === TabSetNode_1.TabSetNode.TYPE) {
                    const child = TabSetNode_1.TabSetNode._fromJson(jsonChild, model);
                    newLayoutNode._addChild(child);
                }
                else {
                    const child = RowNode._fromJson(jsonChild, model);
                    newLayoutNode._addChild(child);
                }
            }
        }
        return newLayoutNode;
    }
    /** @internal */
    static _createAttributeDefinitions() {
        const attributeDefinitions = new AttributeDefinitions_1.AttributeDefinitions();
        attributeDefinitions.add("type", RowNode.TYPE, true).setType(Attribute_1.Attribute.STRING).setFixed();
        attributeDefinitions.add("id", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("weight", 100).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("width", undefined).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("height", undefined).setType(Attribute_1.Attribute.NUMBER);
        return attributeDefinitions;
    }
    /** @internal */
    constructor(model, json) {
        super(model);
        this._dirty = true;
        this._drawChildren = [];
        this._minHeight = 0;
        this._minWidth = 0;
        RowNode._attributeDefinitions.fromJson(json, this._attributes);
        model._addNode(this);
    }
    getWeight() {
        return this._attributes.weight;
    }
    getWidth() {
        return this._getAttr("width");
    }
    getHeight() {
        return this._getAttr("height");
    }
    /** @internal */
    _setWeight(weight) {
        this._attributes.weight = weight;
    }
    /** @internal */
    _layout(rect, metrics) {
        super._layout(rect, metrics);
        const pixelSize = this._rect._getSize(this.getOrientation());
        let totalWeight = 0;
        let fixedPixels = 0;
        let prefPixels = 0;
        let totalPrefWeight = 0;
        const drawChildren = this._getDrawChildren();
        for (const child of drawChildren) {
            const prefSize = child._getPrefSize(this.getOrientation());
            if (child._isFixed()) {
                if (prefSize !== undefined) {
                    fixedPixels += prefSize;
                }
            }
            else {
                if (prefSize === undefined) {
                    totalWeight += child.getWeight();
                }
                else {
                    prefPixels += prefSize;
                    totalPrefWeight += child.getWeight();
                }
            }
        }
        let resizePreferred = false;
        let availablePixels = pixelSize - fixedPixels - prefPixels;
        if (availablePixels < 0) {
            availablePixels = pixelSize - fixedPixels;
            resizePreferred = true;
            totalWeight += totalPrefWeight;
        }
        // assign actual pixel sizes
        let totalSizeGiven = 0;
        let variableSize = 0;
        for (const child of drawChildren) {
            const prefSize = child._getPrefSize(this.getOrientation());
            if (child._isFixed()) {
                if (prefSize !== undefined) {
                    child._setTempSize(prefSize);
                }
            }
            else {
                if (prefSize == null || resizePreferred) {
                    if (totalWeight === 0) {
                        child._setTempSize(0);
                    }
                    else {
                        const minSize = child.getMinSize(this.getOrientation());
                        const size = Math.floor(availablePixels * (child.getWeight() / totalWeight));
                        child._setTempSize(Math.max(minSize, size));
                    }
                    variableSize += child._getTempSize();
                }
                else {
                    child._setTempSize(prefSize);
                }
            }
            totalSizeGiven += child._getTempSize();
        }
        // adjust sizes to exactly fit
        if (variableSize > 0) {
            while (totalSizeGiven < pixelSize) {
                for (const child of drawChildren) {
                    if (!(child instanceof SplitterNode_1.SplitterNode)) {
                        const prefSize = child._getPrefSize(this.getOrientation());
                        if (!child._isFixed() && (prefSize === undefined || resizePreferred) && totalSizeGiven < pixelSize) {
                            child._setTempSize(child._getTempSize() + 1);
                            totalSizeGiven++;
                        }
                    }
                }
            }
            // decrease size using nodes not at there minimum
            while (totalSizeGiven > pixelSize) {
                let changed = false;
                for (const child of drawChildren) {
                    if (!(child instanceof SplitterNode_1.SplitterNode)) {
                        const minSize = child.getMinSize(this.getOrientation());
                        const size = child._getTempSize();
                        if (size > minSize && totalSizeGiven > pixelSize) {
                            child._setTempSize(child._getTempSize() - 1);
                            totalSizeGiven--;
                            changed = true;
                        }
                    }
                }
                if (!changed) {
                    // all children are at min values
                    break;
                }
            }
            // if still too big then simply reduce all nodes until fits
            while (totalSizeGiven > pixelSize) {
                let changed = false;
                for (const child of drawChildren) {
                    if (!(child instanceof SplitterNode_1.SplitterNode)) {
                        const size = child._getTempSize();
                        if (size > 0 && totalSizeGiven > pixelSize) {
                            child._setTempSize(child._getTempSize() - 1);
                            totalSizeGiven--;
                            changed = true;
                        }
                    }
                }
                if (!changed) {
                    // all children are at 0 values
                    break;
                }
            }
        }
        // layout children
        let p = 0;
        for (const child of drawChildren) {
            if (this.getOrientation() === Orientation_1.Orientation.HORZ) {
                child._layout(new Rect_1.Rect(this._rect.x + p, this._rect.y, child._getTempSize(), this._rect.height), metrics);
            }
            else {
                child._layout(new Rect_1.Rect(this._rect.x, this._rect.y + p, this._rect.width, child._getTempSize()), metrics);
            }
            p += child._getTempSize();
        }
        return true;
    }
    /** @internal */
    _getSplitterBounds(splitterNode, useMinSize = false) {
        const pBounds = [0, 0];
        const drawChildren = this._getDrawChildren();
        const p = drawChildren.indexOf(splitterNode);
        const node1 = drawChildren[p - 1];
        const node2 = drawChildren[p + 1];
        if (this.getOrientation() === Orientation_1.Orientation.HORZ) {
            const minSize1 = useMinSize ? node1.getMinWidth() : 0;
            const minSize2 = useMinSize ? node2.getMinWidth() : 0;
            pBounds[0] = node1.getRect().x + minSize1;
            pBounds[1] = node2.getRect().getRight() - splitterNode.getWidth() - minSize2;
        }
        else {
            const minSize1 = useMinSize ? node1.getMinHeight() : 0;
            const minSize2 = useMinSize ? node2.getMinHeight() : 0;
            pBounds[0] = node1.getRect().y + minSize1;
            pBounds[1] = node2.getRect().getBottom() - splitterNode.getHeight() - minSize2;
        }
        return pBounds;
    }
    /** @internal */
    _calculateSplit(splitter, splitterPos) {
        let rtn;
        const drawChildren = this._getDrawChildren();
        const p = drawChildren.indexOf(splitter);
        const pBounds = this._getSplitterBounds(splitter);
        const weightedLength = drawChildren[p - 1].getWeight() + drawChildren[p + 1].getWeight();
        const pixelWidth1 = Math.max(0, splitterPos - pBounds[0]);
        const pixelWidth2 = Math.max(0, pBounds[1] - splitterPos);
        if (pixelWidth1 + pixelWidth2 > 0) {
            const weight1 = (pixelWidth1 * weightedLength) / (pixelWidth1 + pixelWidth2);
            const weight2 = (pixelWidth2 * weightedLength) / (pixelWidth1 + pixelWidth2);
            rtn = {
                node1Id: drawChildren[p - 1].getId(),
                weight1,
                pixelWidth1,
                node2Id: drawChildren[p + 1].getId(),
                weight2,
                pixelWidth2,
            };
        }
        return rtn;
    }
    /** @internal */
    _getDrawChildren() {
        if (this._dirty) {
            this._drawChildren = [];
            for (let i = 0; i < this._children.length; i++) {
                const child = this._children[i];
                if (i !== 0) {
                    const newSplitter = new SplitterNode_1.SplitterNode(this._model);
                    newSplitter._setParent(this);
                    this._drawChildren.push(newSplitter);
                }
                this._drawChildren.push(child);
            }
            this._dirty = false;
        }
        return this._drawChildren;
    }
    /** @internal */
    getMinSize(orientation) {
        if (orientation === Orientation_1.Orientation.HORZ) {
            return this.getMinWidth();
        }
        else {
            return this.getMinHeight();
        }
    }
    /** @internal */
    getMinWidth() {
        return this._minWidth;
    }
    /** @internal */
    getMinHeight() {
        return this._minHeight;
    }
    /** @internal */
    calcMinSize() {
        this._minHeight = 0;
        this._minWidth = 0;
        let first = true;
        for (const child of this._children) {
            const c = child;
            if (c instanceof RowNode) {
                c.calcMinSize();
            }
            if (this.getOrientation() === Orientation_1.Orientation.VERT) {
                this._minHeight += c.getMinHeight();
                if (!first) {
                    this._minHeight += this._model.getSplitterSize();
                }
                this._minWidth = Math.max(this._minWidth, c.getMinWidth());
            }
            else {
                this._minWidth += c.getMinWidth();
                if (!first) {
                    this._minWidth += this._model.getSplitterSize();
                }
                this._minHeight = Math.max(this._minHeight, c.getMinHeight());
            }
            first = false;
        }
    }
    /** @internal */
    _tidy() {
        let i = 0;
        while (i < this._children.length) {
            const child = this._children[i];
            if (child instanceof RowNode) {
                child._tidy();
                const childChildren = child.getChildren();
                if (childChildren.length === 0) {
                    this._removeChild(child);
                }
                else if (childChildren.length === 1) {
                    // hoist child/children up to this level
                    const subchild = childChildren[0];
                    this._removeChild(child);
                    if (subchild instanceof RowNode) {
                        let subChildrenTotal = 0;
                        const subChildChildren = subchild.getChildren();
                        for (const ssc of subChildChildren) {
                            const subsubChild = ssc;
                            subChildrenTotal += subsubChild.getWeight();
                        }
                        for (let j = 0; j < subChildChildren.length; j++) {
                            const subsubChild = subChildChildren[j];
                            subsubChild._setWeight((child.getWeight() * subsubChild.getWeight()) / subChildrenTotal);
                            this._addChild(subsubChild, i + j);
                        }
                    }
                    else {
                        subchild._setWeight(child.getWeight());
                        this._addChild(subchild, i);
                    }
                }
                else {
                    i++;
                }
            }
            else if (child instanceof TabSetNode_1.TabSetNode && child.getChildren().length === 0) {
                if (child.isEnableDeleteWhenEmpty()) {
                    this._removeChild(child);
                    if (child === this._model.getMaximizedTabset()) {
                        this._model._setMaximizedTabset(undefined);
                    }
                }
                else {
                    i++;
                }
            }
            else {
                i++;
            }
        }
        // add tabset into empty root
        if (this === this._model.getRoot() && this._children.length === 0) {
            const callback = this._model._getOnCreateTabSet();
            let attrs = callback ? callback() : {};
            attrs = Object.assign(Object.assign({}, attrs), { selected: -1 });
            const child = new TabSetNode_1.TabSetNode(this._model, attrs);
            this._model._setActiveTabset(child);
            this._addChild(child);
        }
    }
    /** @internal */
    canDrop(dragNode, x, y) {
        const yy = y - this._rect.y;
        const xx = x - this._rect.x;
        const w = this._rect.width;
        const h = this._rect.height;
        const margin = 10; // height of edge rect
        const half = 50; // half width of edge rect
        let dropInfo;
        if (this._model.isEnableEdgeDock() && this._parent === undefined) {
            // _root row
            if (x < this._rect.x + margin && yy > h / 2 - half && yy < h / 2 + half) {
                const dockLocation = DockLocation_1.DockLocation.LEFT;
                const outlineRect = dockLocation.getDockRect(this._rect);
                outlineRect.width = outlineRect.width / 2;
                dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE);
            }
            else if (x > this._rect.getRight() - margin && yy > h / 2 - half && yy < h / 2 + half) {
                const dockLocation = DockLocation_1.DockLocation.RIGHT;
                const outlineRect = dockLocation.getDockRect(this._rect);
                outlineRect.width = outlineRect.width / 2;
                outlineRect.x += outlineRect.width;
                dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE);
            }
            else if (y < this._rect.y + margin && xx > w / 2 - half && xx < w / 2 + half) {
                const dockLocation = DockLocation_1.DockLocation.TOP;
                const outlineRect = dockLocation.getDockRect(this._rect);
                outlineRect.height = outlineRect.height / 2;
                dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE);
            }
            else if (y > this._rect.getBottom() - margin && xx > w / 2 - half && xx < w / 2 + half) {
                const dockLocation = DockLocation_1.DockLocation.BOTTOM;
                const outlineRect = dockLocation.getDockRect(this._rect);
                outlineRect.height = outlineRect.height / 2;
                outlineRect.y += outlineRect.height;
                dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE);
            }
            if (dropInfo !== undefined) {
                if (!dragNode._canDockInto(dragNode, dropInfo)) {
                    return undefined;
                }
            }
        }
        return dropInfo;
    }
    /** @internal */
    drop(dragNode, location, index) {
        const dockLocation = location;
        const parent = dragNode.getParent();
        if (parent) {
            parent._removeChild(dragNode);
        }
        if (parent !== undefined && parent.getType() === TabSetNode_1.TabSetNode.TYPE) {
            parent._setSelected(0);
        }
        if (parent !== undefined && parent.getType() === BorderNode_1.BorderNode.TYPE) {
            parent._setSelected(-1);
        }
        let tabSet;
        if (dragNode instanceof TabSetNode_1.TabSetNode) {
            tabSet = dragNode;
        }
        else {
            const callback = this._model._getOnCreateTabSet();
            tabSet = new TabSetNode_1.TabSetNode(this._model, callback ? callback(dragNode) : {});
            tabSet._addChild(dragNode);
        }
        let size = this._children.reduce((sum, child) => {
            return sum + child.getWeight();
        }, 0);
        if (size === 0) {
            size = 100;
        }
        tabSet._setWeight(size / 3);
        const horz = !this._model.isRootOrientationVertical();
        if (horz && dockLocation === DockLocation_1.DockLocation.LEFT || !horz && dockLocation === DockLocation_1.DockLocation.TOP) {
            this._addChild(tabSet, 0);
        }
        else if (horz && dockLocation === DockLocation_1.DockLocation.RIGHT || !horz && dockLocation === DockLocation_1.DockLocation.BOTTOM) {
            this._addChild(tabSet);
        }
        else if (horz && dockLocation === DockLocation_1.DockLocation.TOP || !horz && dockLocation === DockLocation_1.DockLocation.LEFT) {
            const vrow = new RowNode(this._model, {});
            const hrow = new RowNode(this._model, {});
            hrow._setWeight(75);
            tabSet._setWeight(25);
            for (const child of this._children) {
                hrow._addChild(child);
            }
            this._removeAll();
            vrow._addChild(tabSet);
            vrow._addChild(hrow);
            this._addChild(vrow);
        }
        else if (horz && dockLocation === DockLocation_1.DockLocation.BOTTOM || !horz && dockLocation === DockLocation_1.DockLocation.RIGHT) {
            const vrow = new RowNode(this._model, {});
            const hrow = new RowNode(this._model, {});
            hrow._setWeight(75);
            tabSet._setWeight(25);
            for (const child of this._children) {
                hrow._addChild(child);
            }
            this._removeAll();
            vrow._addChild(hrow);
            vrow._addChild(tabSet);
            this._addChild(vrow);
        }
        this._model._setActiveTabset(tabSet);
        this._model._tidy();
    }
    toJson() {
        const json = {};
        RowNode._attributeDefinitions.toJson(json, this._attributes);
        json.children = [];
        for (const child of this._children) {
            json.children.push(child.toJson());
        }
        return json;
    }
    isEnableDrop() {
        return true;
    }
    /** @internal */
    _getPrefSize(orientation) {
        let prefSize = this.getWidth();
        if (orientation === Orientation_1.Orientation.VERT) {
            prefSize = this.getHeight();
        }
        return prefSize;
    }
    /** @internal */
    _getAttributeDefinitions() {
        return RowNode._attributeDefinitions;
    }
    /** @internal */
    _updateAttrs(json) {
        RowNode._attributeDefinitions.update(json, this._attributes);
    }
    /** @internal */
    static getAttributeDefinitions() {
        return RowNode._attributeDefinitions;
    }
}
exports.RowNode = RowNode;
RowNode.TYPE = "row";
/** @internal */
RowNode._attributeDefinitions = RowNode._createAttributeDefinitions();
//# sourceMappingURL=RowNode.js.map

/***/ }),

/***/ 4976:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
var react__WEBPACK_IMPORTED_MODULE_0___namespace_cache;
var react_dom__WEBPACK_IMPORTED_MODULE_1___namespace_cache;
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   I9: function() { return /* binding */ HashRouter; }
/* harmony export */ });
/* unused harmony exports BrowserRouter, Form, Link, NavLink, RouterProvider, ScrollRestoration, UNSAFE_FetchersContext, UNSAFE_ViewTransitionContext, UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, unstable_HistoryRouter, unstable_usePrompt, unstable_useViewTransitionState, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6540);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(961);
/* harmony import */ var react_router__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7767);
/* harmony import */ var _remix_run_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5588);
/**
 * React Router DOM v6.22.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */






function _extends() {
  _extends = Object.assign ? Object.assign.bind() : 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);
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;
  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }
  return target;
}

const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
  return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
  return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
  return event.button === 0 && (
  // Ignore everything but left clicks
  !target || target === "_self") &&
  // Let browser handle "target=_blank" etc.
  !isModifiedEvent(event) // Ignore clicks with modifier keys
  ;
}
/**
 * Creates a URLSearchParams object using the given initializer.
 *
 * This is identical to `new URLSearchParams(init)` except it also
 * supports arrays as values in the object form of the initializer
 * instead of just strings. This is convenient when you need multiple
 * values for a given key, but don't want to use an array initializer.
 *
 * For example, instead of:
 *
 *   let searchParams = new URLSearchParams([
 *     ['sort', 'name'],
 *     ['sort', 'price']
 *   ]);
 *
 * you can do:
 *
 *   let searchParams = createSearchParams({
 *     sort: ['name', 'price']
 *   });
 */
function createSearchParams(init) {
  if (init === void 0) {
    init = "";
  }
  return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
    let value = init[key];
    return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
  }, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  let searchParams = createSearchParams(locationSearch);
  if (defaultSearchParams) {
    // Use `defaultSearchParams.forEach(...)` here instead of iterating of
    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
    // web extensions. Relevant Bugzilla tickets:
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
    defaultSearchParams.forEach((_, key) => {
      if (!searchParams.has(key)) {
        defaultSearchParams.getAll(key).forEach(value => {
          searchParams.append(key, value);
        });
      }
    });
  }
  return searchParams;
}
// One-time check for submitter support
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
  if (_formDataSupportsSubmitter === null) {
    try {
      new FormData(document.createElement("form"),
      // @ts-expect-error if FormData supports the submitter parameter, this will throw
      0);
      _formDataSupportsSubmitter = false;
    } catch (e) {
      _formDataSupportsSubmitter = true;
    }
  }
  return _formDataSupportsSubmitter;
}
const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
function getFormEncType(encType) {
  if (encType != null && !supportedFormEncTypes.has(encType)) {
     false ? 0 : void 0;
    return null;
  }
  return encType;
}
function getFormSubmissionInfo(target, basename) {
  let method;
  let action;
  let encType;
  let formData;
  let body;
  if (isFormElement(target)) {
    // When grabbing the action from the element, it will have had the basename
    // prefixed to ensure non-JS scenarios work, so strip it since we'll
    // re-prefix in the router
    let attr = target.getAttribute("action");
    action = attr ? stripBasename(attr, basename) : null;
    method = target.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(target);
  } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
    let form = target.form;
    if (form == null) {
      throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
    }
    // <button>/<input type="submit"> may override attributes of <form>
    // When grabbing the action from the element, it will have had the basename
    // prefixed to ensure non-JS scenarios work, so strip it since we'll
    // re-prefix in the router
    let attr = target.getAttribute("formaction") || form.getAttribute("action");
    action = attr ? stripBasename(attr, basename) : null;
    method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
    // Build a FormData object populated from a form and submitter
    formData = new FormData(form, target);
    // If this browser doesn't support the `FormData(el, submitter)` format,
    // then tack on the submitter value at the end.  This is a lightweight
    // solution that is not 100% spec compliant.  For complete support in older
    // browsers, consider using the `formdata-submitter-polyfill` package
    if (!isFormDataSubmitterSupported()) {
      let {
        name,
        type,
        value
      } = target;
      if (type === "image") {
        let prefix = name ? name + "." : "";
        formData.append(prefix + "x", "0");
        formData.append(prefix + "y", "0");
      } else if (name) {
        formData.append(name, value);
      }
    }
  } else if (isHtmlElement(target)) {
    throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
  } else {
    method = defaultMethod;
    action = null;
    encType = defaultEncType;
    body = target;
  }
  // Send body for <Form encType="text/plain" so we encode it into text
  if (formData && encType === "text/plain") {
    body = formData;
    formData = undefined;
  }
  return {
    action,
    method: method.toLowerCase(),
    encType,
    formData,
    body
  };
}

const _excluded = (/* unused pure expression or super */ null && (["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "unstable_viewTransition"])),
  _excluded2 = (/* unused pure expression or super */ null && (["aria-current", "caseSensitive", "className", "end", "style", "to", "unstable_viewTransition", "children"])),
  _excluded3 = (/* unused pure expression or super */ null && (["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "unstable_viewTransition"]));
// HEY YOU! DON'T TOUCH THIS VARIABLE!
//
// It is replaced with the proper version at build time via a babel plugin in
// the rollup config.
//
// Export a global property onto the window for React Router detection by the
// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`
// to detect and properly classify live websites as being built with React Router:
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
const REACT_ROUTER_VERSION = "6";
try {
  window.__reactRouterVersion = REACT_ROUTER_VERSION;
} catch (e) {
  // no-op
}
function createBrowserRouter(routes, opts) {
  return createRouter({
    basename: opts == null ? void 0 : opts.basename,
    future: _extends({}, opts == null ? void 0 : opts.future, {
      v7_prependBasename: true
    }),
    history: createBrowserHistory({
      window: opts == null ? void 0 : opts.window
    }),
    hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
    routes,
    mapRouteProperties: UNSAFE_mapRouteProperties,
    window: opts == null ? void 0 : opts.window
  }).initialize();
}
function createHashRouter(routes, opts) {
  return createRouter({
    basename: opts == null ? void 0 : opts.basename,
    future: _extends({}, opts == null ? void 0 : opts.future, {
      v7_prependBasename: true
    }),
    history: createHashHistory({
      window: opts == null ? void 0 : opts.window
    }),
    hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
    routes,
    mapRouteProperties: UNSAFE_mapRouteProperties,
    window: opts == null ? void 0 : opts.window
  }).initialize();
}
function parseHydrationData() {
  var _window;
  let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
  if (state && state.errors) {
    state = _extends({}, state, {
      errors: deserializeErrors(state.errors)
    });
  }
  return state;
}
function deserializeErrors(errors) {
  if (!errors) return null;
  let entries = Object.entries(errors);
  let serialized = {};
  for (let [key, val] of entries) {
    // Hey you!  If you change this, please change the corresponding logic in
    // serializeErrors in react-router-dom/server.tsx :)
    if (val && val.__type === "RouteErrorResponse") {
      serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
    } else if (val && val.__type === "Error") {
      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
      if (val.__subType) {
        let ErrorConstructor = window[val.__subType];
        if (typeof ErrorConstructor === "function") {
          try {
            // @ts-expect-error
            let error = new ErrorConstructor(val.message);
            // Wipe away the client-side stack trace.  Nothing to fill it in with
            // because we don't serialize SSR stack traces for security reasons
            error.stack = "";
            serialized[key] = error;
          } catch (e) {
            // no-op - fall through and create a normal Error
          }
        }
      }
      if (serialized[key] == null) {
        let error = new Error(val.message);
        // Wipe away the client-side stack trace.  Nothing to fill it in with
        // because we don't serialize SSR stack traces for security reasons
        error.stack = "";
        serialized[key] = error;
      }
    } else {
      serialized[key] = val;
    }
  }
  return serialized;
}
const ViewTransitionContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext({
  isTransitioning: false
});
if (false) // removed by dead control flow
{}
const FetchersContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(new Map());
if (false) // removed by dead control flow
{}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
  Webpack + React 17 fails to compile on any of the following because webpack
  complains that `startTransition` doesn't exist in `React`:
  * import { startTransition } from "react"
  * import * as React from from "react";
    "startTransition" in React ? React.startTransition(() => setState()) : setState()
  * import * as React from from "react";
    "startTransition" in React ? React["startTransition"](() => setState()) : setState()

  Moving it to a constant such as the following solves the Webpack/React 17 issue:
  * import * as React from from "react";
    const START_TRANSITION = "startTransition";
    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

  However, that introduces webpack/terser minification issues in production builds
  in React 18 where minification/obfuscation ends up removing the call of
  React.startTransition entirely from the first half of the ternary.  Grabbing
  this exported reference once up front resolves that issue.

  See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = /*#__PURE__*/ (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_0__, 2)))[START_TRANSITION];
const FLUSH_SYNC = "flushSync";
const flushSyncImpl = /*#__PURE__*/ (react_dom__WEBPACK_IMPORTED_MODULE_1___namespace_cache || (react_dom__WEBPACK_IMPORTED_MODULE_1___namespace_cache = __webpack_require__.t(react_dom__WEBPACK_IMPORTED_MODULE_1__, 2)))[FLUSH_SYNC];
const USE_ID = "useId";
const useIdImpl = /*#__PURE__*/ (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_0__, 2)))[USE_ID];
function startTransitionSafe(cb) {
  if (startTransitionImpl) {
    startTransitionImpl(cb);
  } else {
    cb();
  }
}
function flushSyncSafe(cb) {
  if (flushSyncImpl) {
    flushSyncImpl(cb);
  } else {
    cb();
  }
}
class Deferred {
  constructor() {
    this.status = "pending";
    this.promise = new Promise((resolve, reject) => {
      this.resolve = value => {
        if (this.status === "pending") {
          this.status = "resolved";
          resolve(value);
        }
      };
      this.reject = reason => {
        if (this.status === "pending") {
          this.status = "rejected";
          reject(reason);
        }
      };
    });
  }
}
/**
 * Given a Remix Router instance, render the appropriate UI
 */
function RouterProvider(_ref) {
  let {
    fallbackElement,
    router,
    future
  } = _ref;
  let [state, setStateImpl] = React.useState(router.state);
  let [pendingState, setPendingState] = React.useState();
  let [vtContext, setVtContext] = React.useState({
    isTransitioning: false
  });
  let [renderDfd, setRenderDfd] = React.useState();
  let [transition, setTransition] = React.useState();
  let [interruption, setInterruption] = React.useState();
  let fetcherData = React.useRef(new Map());
  let {
    v7_startTransition
  } = future || {};
  let optInStartTransition = React.useCallback(cb => {
    if (v7_startTransition) {
      startTransitionSafe(cb);
    } else {
      cb();
    }
  }, [v7_startTransition]);
  let setState = React.useCallback((newState, _ref2) => {
    let {
      deletedFetchers,
      unstable_flushSync: flushSync,
      unstable_viewTransitionOpts: viewTransitionOpts
    } = _ref2;
    deletedFetchers.forEach(key => fetcherData.current.delete(key));
    newState.fetchers.forEach((fetcher, key) => {
      if (fetcher.data !== undefined) {
        fetcherData.current.set(key, fetcher.data);
      }
    });
    let isViewTransitionUnavailable = router.window == null || typeof router.window.document.startViewTransition !== "function";
    // If this isn't a view transition or it's not available in this browser,
    // just update and be done with it
    if (!viewTransitionOpts || isViewTransitionUnavailable) {
      if (flushSync) {
        flushSyncSafe(() => setStateImpl(newState));
      } else {
        optInStartTransition(() => setStateImpl(newState));
      }
      return;
    }
    // flushSync + startViewTransition
    if (flushSync) {
      // Flush through the context to mark DOM elements as transition=ing
      flushSyncSafe(() => {
        // Cancel any pending transitions
        if (transition) {
          renderDfd && renderDfd.resolve();
          transition.skipTransition();
        }
        setVtContext({
          isTransitioning: true,
          flushSync: true,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      });
      // Update the DOM
      let t = router.window.document.startViewTransition(() => {
        flushSyncSafe(() => setStateImpl(newState));
      });
      // Clean up after the animation completes
      t.finished.finally(() => {
        flushSyncSafe(() => {
          setRenderDfd(undefined);
          setTransition(undefined);
          setPendingState(undefined);
          setVtContext({
            isTransitioning: false
          });
        });
      });
      flushSyncSafe(() => setTransition(t));
      return;
    }
    // startTransition + startViewTransition
    if (transition) {
      // Interrupting an in-progress transition, cancel and let everything flush
      // out, and then kick off a new transition from the interruption state
      renderDfd && renderDfd.resolve();
      transition.skipTransition();
      setInterruption({
        state: newState,
        currentLocation: viewTransitionOpts.currentLocation,
        nextLocation: viewTransitionOpts.nextLocation
      });
    } else {
      // Completed navigation update with opted-in view transitions, let 'er rip
      setPendingState(newState);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: viewTransitionOpts.currentLocation,
        nextLocation: viewTransitionOpts.nextLocation
      });
    }
  }, [router.window, transition, renderDfd, fetcherData, optInStartTransition]);
  // Need to use a layout effect here so we are subscribed early enough to
  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  // When we start a view transition, create a Deferred we can use for the
  // eventual "completed" render
  React.useEffect(() => {
    if (vtContext.isTransitioning && !vtContext.flushSync) {
      setRenderDfd(new Deferred());
    }
  }, [vtContext]);
  // Once the deferred is created, kick off startViewTransition() to update the
  // DOM and then wait on the Deferred to resolve (indicating the DOM update has
  // happened)
  React.useEffect(() => {
    if (renderDfd && pendingState && router.window) {
      let newState = pendingState;
      let renderPromise = renderDfd.promise;
      let transition = router.window.document.startViewTransition(async () => {
        optInStartTransition(() => setStateImpl(newState));
        await renderPromise;
      });
      transition.finished.finally(() => {
        setRenderDfd(undefined);
        setTransition(undefined);
        setPendingState(undefined);
        setVtContext({
          isTransitioning: false
        });
      });
      setTransition(transition);
    }
  }, [optInStartTransition, pendingState, renderDfd, router.window]);
  // When the new location finally renders and is committed to the DOM, this
  // effect will run to resolve the transition
  React.useEffect(() => {
    if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
      renderDfd.resolve();
    }
  }, [renderDfd, transition, state.location, pendingState]);
  // If we get interrupted with a new navigation during a transition, we skip
  // the active transition, let it cleanup, then kick it off again here
  React.useEffect(() => {
    if (!vtContext.isTransitioning && interruption) {
      setPendingState(interruption.state);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: interruption.currentLocation,
        nextLocation: interruption.nextLocation
      });
      setInterruption(undefined);
    }
  }, [vtContext.isTransitioning, interruption]);
  React.useEffect(() => {
     false ? 0 : void 0;
    // Only log this once on initial mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  let navigator = React.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: n => router.navigate(n),
      push: (to, state, opts) => router.navigate(to, {
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      }),
      replace: (to, state, opts) => router.navigate(to, {
        replace: true,
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      })
    };
  }, [router]);
  let basename = router.basename || "/";
  let dataRouterContext = React.useMemo(() => ({
    router,
    navigator,
    static: false,
    basename
  }), [router, navigator, basename]);
  // The fragment and {null} here are important!  We need them to keep React 18's
  // useId happy when we are server-rendering since we may have a <script> here
  // containing the hydrated server-side staticContext (from StaticRouterProvider).
  // useId relies on the component tree structure to generate deterministic id's
  // so we need to ensure it remains the same on the client even though
  // we don't need the <script> tag
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(FetchersContext.Provider, {
    value: fetcherData.current
  }, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, {
    value: vtContext
  }, /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: navigator,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  }) : fallbackElement))))), null);
}
function DataRoutes(_ref3) {
  let {
    routes,
    future,
    state
  } = _ref3;
  return UNSAFE_useRoutesImpl(routes, undefined, state, future);
}
/**
 * A `<Router>` for use in web browsers. Provides the cleanest URLs.
 */
function BrowserRouter(_ref4) {
  let {
    basename,
    children,
    future,
    window
  } = _ref4;
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createBrowserHistory({
      window,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * A `<Router>` for use in web browsers. Stores the location in the hash
 * portion of the URL so it is not sent to the server.
 */
function HashRouter(_ref5) {
  let {
    basename,
    children,
    future,
    window
  } = _ref5;
  let historyRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef();
  if (historyRef.current == null) {
    historyRef.current = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_3__/* .createHashHistory */ .TM)({
      window,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = react__WEBPACK_IMPORTED_MODULE_0__.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = react__WEBPACK_IMPORTED_MODULE_0__.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect(() => history.listen(setState), [history, setState]);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(react_router__WEBPACK_IMPORTED_MODULE_2__/* .Router */ .Ix, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * A `<Router>` that accepts a pre-instantiated history object. It's important
 * to note that using your own history object is highly discouraged and may add
 * two versions of the history library to your bundles unless you use the same
 * version of the history library that React Router uses internally.
 */
function HistoryRouter(_ref6) {
  let {
    basename,
    children,
    future,
    history
  } = _ref6;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
if (false) // removed by dead control flow
{}
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
/**
 * The public API for rendering a history-aware `<a>`.
 */
const Link = /*#__PURE__*/(/* unused pure expression or super */ null && (React.forwardRef(function LinkWithRef(_ref7, ref) {
  let {
      onClick,
      relative,
      reloadDocument,
      replace,
      state,
      target,
      to,
      preventScrollReset,
      unstable_viewTransition
    } = _ref7,
    rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  // Rendered into <a href> for absolute URLs
  let absoluteHref;
  let isExternal = false;
  if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
    // Render the absolute href server- and client-side
    absoluteHref = to;
    // Only check for external origins client-side
    if (isBrowser) {
      try {
        let currentUrl = new URL(window.location.href);
        let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
        let path = stripBasename(targetUrl.pathname, basename);
        if (targetUrl.origin === currentUrl.origin && path != null) {
          // Strip the protocol/origin/basename for same-origin absolute URLs
          to = path + targetUrl.search + targetUrl.hash;
        } else {
          isExternal = true;
        }
      } catch (e) {
        // We can't do external URL detection without a valid URL
         false ? 0 : void 0;
      }
    }
  }
  // Rendered into <a href> for relative URLs
  let href = useHref(to, {
    relative
  });
  let internalOnClick = useLinkClickHandler(to, {
    replace,
    state,
    target,
    preventScrollReset,
    relative,
    unstable_viewTransition
  });
  function handleClick(event) {
    if (onClick) onClick(event);
    if (!event.defaultPrevented) {
      internalOnClick(event);
    }
  }
  return (
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/anchor-has-content
    React.createElement("a", _extends({}, rest, {
      href: absoluteHref || href,
      onClick: isExternal || reloadDocument ? onClick : handleClick,
      ref: ref,
      target: target
    }))
  );
})));
if (false) // removed by dead control flow
{}
/**
 * A `<Link>` wrapper that knows if it's "active" or not.
 */
const NavLink = /*#__PURE__*/(/* unused pure expression or super */ null && (React.forwardRef(function NavLinkWithRef(_ref8, ref) {
  let {
      "aria-current": ariaCurrentProp = "page",
      caseSensitive = false,
      className: classNameProp = "",
      end = false,
      style: styleProp,
      to,
      unstable_viewTransition,
      children
    } = _ref8,
    rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
  let path = useResolvedPath(to, {
    relative: rest.relative
  });
  let location = useLocation();
  let routerState = React.useContext(UNSAFE_DataRouterStateContext);
  let {
    navigator,
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let isTransitioning = routerState != null &&
  // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useViewTransitionState(path) && unstable_viewTransition === true;
  let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  let locationPathname = location.pathname;
  let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  if (!caseSensitive) {
    locationPathname = locationPathname.toLowerCase();
    nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
    toPathname = toPathname.toLowerCase();
  }
  if (nextLocationPathname && basename) {
    nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  }
  // If the `to` has a trailing slash, look at that exact spot.  Otherwise,
  // we're looking for a slash _after_ what's in `to`.  For example:
  //
  // <NavLink to="/users"> and <NavLink to="/users/">
  // both want to look for a / at index 6 to match URL `/users/matt`
  const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  let renderProps = {
    isActive,
    isPending,
    isTransitioning
  };
  let ariaCurrent = isActive ? ariaCurrentProp : undefined;
  let className;
  if (typeof classNameProp === "function") {
    className = classNameProp(renderProps);
  } else {
    // If the className prop is not a function, we use a default `active`
    // class for <NavLink />s that are active. In v5 `active` was the default
    // value for `activeClassName`, but we are removing that API and can still
    // use the old default behavior for a cleaner upgrade path and keep the
    // simple styling rules working as they currently do.
    className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
  }
  let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
    "aria-current": ariaCurrent,
    className: className,
    ref: ref,
    style: style,
    to: to,
    unstable_viewTransition: unstable_viewTransition
  }), typeof children === "function" ? children(renderProps) : children);
})));
if (false) // removed by dead control flow
{}
/**
 * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
 * that the interaction with the server is with `fetch` instead of new document
 * requests, allowing components to add nicer UX to the page as the form is
 * submitted and returns with data.
 */
const Form = /*#__PURE__*/(/* unused pure expression or super */ null && (React.forwardRef((_ref9, forwardedRef) => {
  let {
      fetcherKey,
      navigate,
      reloadDocument,
      replace,
      state,
      method = defaultMethod,
      action,
      onSubmit,
      relative,
      preventScrollReset,
      unstable_viewTransition
    } = _ref9,
    props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
  let submit = useSubmit();
  let formAction = useFormAction(action, {
    relative
  });
  let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  let submitHandler = event => {
    onSubmit && onSubmit(event);
    if (event.defaultPrevented) return;
    event.preventDefault();
    let submitter = event.nativeEvent.submitter;
    let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
    submit(submitter || event.currentTarget, {
      fetcherKey,
      method: submitMethod,
      navigate,
      replace,
      state,
      relative,
      preventScrollReset,
      unstable_viewTransition
    });
  };
  return /*#__PURE__*/React.createElement("form", _extends({
    ref: forwardedRef,
    method: formMethod,
    action: formAction,
    onSubmit: reloadDocument ? onSubmit : submitHandler
  }, props));
})));
if (false) // removed by dead control flow
{}
/**
 * This component will emulate the browser's scroll restoration on location
 * changes.
 */
function ScrollRestoration(_ref10) {
  let {
    getKey,
    storageKey
  } = _ref10;
  useScrollRestoration({
    getKey,
    storageKey
  });
  return null;
}
if (false) // removed by dead control flow
{}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook;
(function (DataRouterHook) {
  DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
  DataRouterHook["UseSubmit"] = "useSubmit";
  DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
  DataRouterHook["UseFetcher"] = "useFetcher";
  DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
  DataRouterStateHook["UseFetcher"] = "useFetcher";
  DataRouterStateHook["UseFetchers"] = "useFetchers";
  DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
})(DataRouterStateHook || (DataRouterStateHook = {}));
// Internal hooks
function getDataRouterConsoleError(hookName) {
  return hookName + " must be used within a data router.  See https://reactrouter.com/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
  let ctx = React.useContext(UNSAFE_DataRouterContext);
  !ctx ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = React.useContext(UNSAFE_DataRouterStateContext);
  !state ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  return state;
}
// External hooks
/**
 * Handles the click behavior for router `<Link>` components. This is useful if
 * you need to create custom `<Link>` components with the same click behavior we
 * use in our exported `<Link>`.
 */
function useLinkClickHandler(to, _temp) {
  let {
    target,
    replace: replaceProp,
    state,
    preventScrollReset,
    relative,
    unstable_viewTransition
  } = _temp === void 0 ? {} : _temp;
  let navigate = useNavigate();
  let location = useLocation();
  let path = useResolvedPath(to, {
    relative
  });
  return React.useCallback(event => {
    if (shouldProcessLinkClick(event, target)) {
      event.preventDefault();
      // If the URL hasn't changed, a regular <a> will do a replace instead of
      // a push, so do the same here unless the replace prop is explicitly set
      let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
      navigate(to, {
        replace,
        state,
        preventScrollReset,
        relative,
        unstable_viewTransition
      });
    }
  }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, unstable_viewTransition]);
}
/**
 * A convenient wrapper for reading and writing search parameters via the
 * URLSearchParams interface.
 */
function useSearchParams(defaultInit) {
   false ? 0 : void 0;
  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
  let hasSetSearchParamsRef = React.useRef(false);
  let location = useLocation();
  let searchParams = React.useMemo(() =>
  // Only merge in the defaults if we haven't yet called setSearchParams.
  // Once we call that we want those to take precedence, otherwise you can't
  // remove a param with setSearchParams({}) if it has an initial value
  getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
  let navigate = useNavigate();
  let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
    const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
    hasSetSearchParamsRef.current = true;
    navigate("?" + newSearchParams, navigateOptions);
  }, [navigate, searchParams]);
  return [searchParams, setSearchParams];
}
function validateClientSideSubmission() {
  if (typeof document === "undefined") {
    throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
  }
}
let fetcherId = 0;
let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
/**
 * Returns a function that may be used to programmatically submit a form (or
 * some arbitrary data) to the server.
 */
function useSubmit() {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseSubmit);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let currentRouteId = UNSAFE_useRouteId();
  return React.useCallback(function (target, options) {
    if (options === void 0) {
      options = {};
    }
    validateClientSideSubmission();
    let {
      action,
      method,
      encType,
      formData,
      body
    } = getFormSubmissionInfo(target, basename);
    if (options.navigate === false) {
      let key = options.fetcherKey || getUniqueFetcherId();
      router.fetch(key, currentRouteId, options.action || action, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        unstable_flushSync: options.unstable_flushSync
      });
    } else {
      router.navigate(options.action || action, {
        preventScrollReset: options.preventScrollReset,
        formData,
        body,
        formMethod: options.method || method,
        formEncType: options.encType || encType,
        replace: options.replace,
        state: options.state,
        fromRouteId: currentRouteId,
        unstable_flushSync: options.unstable_flushSync,
        unstable_viewTransition: options.unstable_viewTransition
      });
    }
  }, [router, basename, currentRouteId]);
}
// v7: Eventually we should deprecate this entirely in favor of using the
// router method directly?
function useFormAction(action, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let routeContext = React.useContext(UNSAFE_RouteContext);
  !routeContext ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  let [match] = routeContext.matches.slice(-1);
  // Shallow clone path so we can modify it below, otherwise we modify the
  // object referenced by useMemo inside useResolvedPath
  let path = _extends({}, useResolvedPath(action ? action : ".", {
    relative
  }));
  // If no action was specified, browsers will persist current search params
  // when determining the path, so match that behavior
  // https://github.com/remix-run/remix/issues/927
  let location = useLocation();
  if (action == null) {
    // Safe to write to this directly here since if action was undefined, we
    // would have called useResolvedPath(".") which will never include a search
    path.search = location.search;
    // When grabbing search params from the URL, remove any included ?index param
    // since it might not apply to our contextual route.  We add it back based
    // on match.route.index below
    let params = new URLSearchParams(path.search);
    if (params.has("index") && params.get("index") === "") {
      params.delete("index");
      path.search = params.toString() ? "?" + params.toString() : "";
    }
  }
  if ((!action || action === ".") && match.route.index) {
    path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  }
  // If we're operating within a basename, prepend it to the pathname prior
  // to creating the form action.  If this is a root navigation, then just use
  // the raw basename which allows the basename to have full control over the
  // presence of a trailing slash on root actions
  if (basename !== "/") {
    path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }
  return createPath(path);
}
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`
/**
 * Interacts with route loaders and actions without causing a navigation. Great
 * for any interaction that stays on the same page.
 */
function useFetcher(_temp3) {
  var _route$matches;
  let {
    key
  } = _temp3 === void 0 ? {} : _temp3;
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseFetcher);
  let state = useDataRouterState(DataRouterStateHook.UseFetcher);
  let fetcherData = React.useContext(FetchersContext);
  let route = React.useContext(UNSAFE_RouteContext);
  let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
  !fetcherData ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  !route ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  !(routeId != null) ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  // Fetcher key handling
  // OK to call conditionally to feature detect `useId`
  // eslint-disable-next-line react-hooks/rules-of-hooks
  let defaultKey = useIdImpl ? useIdImpl() : "";
  let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey);
  if (key && key !== fetcherKey) {
    setFetcherKey(key);
  } else if (!fetcherKey) {
    // We will only fall through here when `useId` is not available
    setFetcherKey(getUniqueFetcherId());
  }
  // Registration/cleanup
  React.useEffect(() => {
    router.getFetcher(fetcherKey);
    return () => {
      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
      // will not delete immediately but instead queue up a delete after the
      // fetcher returns to an `idle` state
      router.deleteFetcher(fetcherKey);
    };
  }, [router, fetcherKey]);
  // Fetcher additions
  let load = React.useCallback((href, opts) => {
    !routeId ?  false ? 0 : UNSAFE_invariant(false) : void 0;
    router.fetch(fetcherKey, routeId, href, opts);
  }, [fetcherKey, routeId, router]);
  let submitImpl = useSubmit();
  let submit = React.useCallback((target, opts) => {
    submitImpl(target, _extends({}, opts, {
      navigate: false,
      fetcherKey
    }));
  }, [fetcherKey, submitImpl]);
  let FetcherForm = React.useMemo(() => {
    let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
      return /*#__PURE__*/React.createElement(Form, _extends({}, props, {
        navigate: false,
        fetcherKey: fetcherKey,
        ref: ref
      }));
    });
    if (false) // removed by dead control flow
{}
    return FetcherForm;
  }, [fetcherKey]);
  // Exposed FetcherWithComponents
  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  let data = fetcherData.get(fetcherKey);
  let fetcherWithComponents = React.useMemo(() => _extends({
    Form: FetcherForm,
    submit,
    load
  }, fetcher, {
    data
  }), [FetcherForm, submit, load, fetcher, data]);
  return fetcherWithComponents;
}
/**
 * Provides all fetchers currently on the page. Useful for layouts and parent
 * routes that need to provide pending/optimistic UI regarding the fetch.
 */
function useFetchers() {
  let state = useDataRouterState(DataRouterStateHook.UseFetchers);
  return Array.from(state.fetchers.entries()).map(_ref11 => {
    let [key, fetcher] = _ref11;
    return _extends({}, fetcher, {
      key
    });
  });
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
 * When rendered inside a RouterProvider, will restore scroll positions on navigations
 */
function useScrollRestoration(_temp4) {
  let {
    getKey,
    storageKey
  } = _temp4 === void 0 ? {} : _temp4;
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
  let {
    restoreScrollPosition,
    preventScrollReset
  } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
  let {
    basename
  } = React.useContext(UNSAFE_NavigationContext);
  let location = useLocation();
  let matches = useMatches();
  let navigation = useNavigation();
  // Trigger manual scroll restoration while we're active
  React.useEffect(() => {
    window.history.scrollRestoration = "manual";
    return () => {
      window.history.scrollRestoration = "auto";
    };
  }, []);
  // Save positions on pagehide
  usePageHide(React.useCallback(() => {
    if (navigation.state === "idle") {
      let key = (getKey ? getKey(location, matches) : null) || location.key;
      savedScrollPositions[key] = window.scrollY;
    }
    try {
      sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
    } catch (error) {
       false ? 0 : void 0;
    }
    window.history.scrollRestoration = "auto";
  }, [storageKey, getKey, navigation.state, location, matches]));
  // Read in any saved scroll locations
  if (typeof document !== "undefined") {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      try {
        let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
        if (sessionPositions) {
          savedScrollPositions = JSON.parse(sessionPositions);
        }
      } catch (e) {
        // no-op, use default empty object
      }
    }, [storageKey]);
    // Enable scroll restoration in the router
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( // Strip the basename to match useLocation()
      _extends({}, location, {
        pathname: stripBasename(location.pathname, basename) || location.pathname
      }), matches) : getKey;
      let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
      return () => disableScrollRestoration && disableScrollRestoration();
    }, [router, basename, getKey]);
    // Restore scrolling when state.restoreScrollPosition changes
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useLayoutEffect(() => {
      // Explicit false means don't do anything (used for submissions)
      if (restoreScrollPosition === false) {
        return;
      }
      // been here before, scroll to it
      if (typeof restoreScrollPosition === "number") {
        window.scrollTo(0, restoreScrollPosition);
        return;
      }
      // try to scroll to the hash
      if (location.hash) {
        let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
        if (el) {
          el.scrollIntoView();
          return;
        }
      }
      // Don't reset if this navigation opted out
      if (preventScrollReset === true) {
        return;
      }
      // otherwise go to the top on new locations
      window.scrollTo(0, 0);
    }, [location, restoreScrollPosition, preventScrollReset]);
  }
}
/**
 * Setup a callback to be fired on the window's `beforeunload` event. This is
 * useful for saving some data to `window.localStorage` just before the page
 * refreshes.
 *
 * Note: The `callback` argument should be a function created with
 * `React.useCallback()`.
 */
function useBeforeUnload(callback, options) {
  let {
    capture
  } = options || {};
  React.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : undefined;
    window.addEventListener("beforeunload", callback, opts);
    return () => {
      window.removeEventListener("beforeunload", callback, opts);
    };
  }, [callback, capture]);
}
/**
 * Setup a callback to be fired on the window's `pagehide` event. This is
 * useful for saving some data to `window.localStorage` just before the page
 * refreshes.  This event is better supported than beforeunload across browsers.
 *
 * Note: The `callback` argument should be a function created with
 * `React.useCallback()`.
 */
function usePageHide(callback, options) {
  let {
    capture
  } = options || {};
  React.useEffect(() => {
    let opts = capture != null ? {
      capture
    } : undefined;
    window.addEventListener("pagehide", callback, opts);
    return () => {
      window.removeEventListener("pagehide", callback, opts);
    };
  }, [callback, capture]);
}
/**
 * Wrapper around useBlocker to show a window.confirm prompt to users instead
 * of building a custom UI with useBlocker.
 *
 * Warning: This has *a lot of rough edges* and behaves very differently (and
 * very incorrectly in some cases) across browsers if user click addition
 * back/forward navigations while the confirm is open.  Use at your own risk.
 */
function usePrompt(_ref12) {
  let {
    when,
    message
  } = _ref12;
  let blocker = useBlocker(when);
  React.useEffect(() => {
    if (blocker.state === "blocked") {
      let proceed = window.confirm(message);
      if (proceed) {
        // This timeout is needed to avoid a weird "race" on POP navigations
        // between the `window.history` revert navigation and the result of
        // `window.confirm`
        setTimeout(blocker.proceed, 0);
      } else {
        blocker.reset();
      }
    }
  }, [blocker, message]);
  React.useEffect(() => {
    if (blocker.state === "blocked" && !when) {
      blocker.reset();
    }
  }, [blocker, when]);
}
/**
 * Return a boolean indicating if there is an active view transition to the
 * given href.  You can use this value to render CSS classes or viewTransitionName
 * styles onto your elements
 *
 * @param href The destination href
 * @param [opts.relative] Relative routing type ("route" | "path")
 */
function useViewTransitionState(to, opts) {
  if (opts === void 0) {
    opts = {};
  }
  let vtContext = React.useContext(ViewTransitionContext);
  !(vtContext != null) ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  let {
    basename
  } = useDataRouterContext(DataRouterHook.useViewTransitionState);
  let path = useResolvedPath(to, {
    relative: opts.relative
  });
  if (!vtContext.isTransitioning) {
    return false;
  }
  let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
  // Transition is active if we're going to or coming from the indicated
  // destination.  This ensures that other PUSH navigations that reverse
  // an indicated transition apply.  I.e., on the list view you have:
  //
  //   <NavLink to="/details/1" unstable_viewTransition>
  //
  // If you click the breadcrumb back to the list view:
  //
  //   <NavLink to="/list" unstable_viewTransition>
  //
  // We should apply the transition because it's indicated as active going
  // from /list -> /details/1 and therefore should be active on the reverse
  // (even though this isn't strictly a POP reverse)
  return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
}
//#endregion


//# sourceMappingURL=index.js.map


/***/ }),

/***/ 4994:
/***/ (function(module) {

function _interopRequireDefault(e) {
  return e && e.__esModule ? e : {
    "default": e
  };
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;

/***/ }),

/***/ 5316:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  n4: function() { return /* binding */ popper_createPopper; }
});

// UNUSED EXPORTS: applyStyles, arrow, computeStyles, createPopperLite, defaultModifiers, detectOverflow, eventListeners, flip, hide, offset, popperGenerator, popperOffsets, preventOverflow

;// ./node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow(node) {
  if (node == null) {
    return window;
  }

  if (node.toString() !== '[object Window]') {
    var ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }

  return node;
}
;// ./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js


function isElement(node) {
  var OwnElement = getWindow(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}

function isHTMLElement(node) {
  var OwnElement = getWindow(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}

function isShadowRoot(node) {
  // IE 11 has no ShadowRoot
  if (typeof ShadowRoot === 'undefined') {
    return false;
  }

  var OwnElement = getWindow(node).ShadowRoot;
  return node instanceof OwnElement || node instanceof ShadowRoot;
}


;// ./node_modules/@popperjs/core/lib/utils/math.js
var math_max = Math.max;
var math_min = Math.min;
var round = Math.round;
;// ./node_modules/@popperjs/core/lib/utils/userAgent.js
function getUAString() {
  var uaData = navigator.userAgentData;

  if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
    return uaData.brands.map(function (item) {
      return item.brand + "/" + item.version;
    }).join(' ');
  }

  return navigator.userAgent;
}
;// ./node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js

function isLayoutViewport() {
  return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js




function getBoundingClientRect(element, includeScale, isFixedStrategy) {
  if (includeScale === void 0) {
    includeScale = false;
  }

  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }

  var clientRect = element.getBoundingClientRect();
  var scaleX = 1;
  var scaleY = 1;

  if (includeScale && isHTMLElement(element)) {
    scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
    scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
  }

  var _ref = isElement(element) ? getWindow(element) : window,
      visualViewport = _ref.visualViewport;

  var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
  var width = clientRect.width / scaleX;
  var height = clientRect.height / scaleY;
  return {
    width: width,
    height: height,
    top: y,
    right: x + width,
    bottom: y + height,
    left: x,
    x: x,
    y: y
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js

function getWindowScroll(node) {
  var win = getWindow(node);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft: scrollLeft,
    scrollTop: scrollTop
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
function getHTMLElementScroll(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js




function getNodeScroll(node) {
  if (node === getWindow(node) || !isHTMLElement(node)) {
    return getWindowScroll(node);
  } else {
    return getHTMLElementScroll(node);
  }
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName(element) {
  return element ? (element.nodeName || '').toLowerCase() : null;
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js

function getDocumentElement(element) {
  // $FlowFixMe[incompatible-return]: assume body is always available
  return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
  element.document) || window.document).documentElement;
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js



function getWindowScrollBarX(element) {
  // If <html> has a CSS width greater than the viewport, then this will be
  // incorrect for RTL.
  // Popper 1 is broken in this case and never had a bug report so let's assume
  // it's not an issue. I don't think anyone ever specifies width on <html>
  // anyway.
  // Browsers where the left scrollbar doesn't cause an issue report `0` for
  // this (e.g. Edge 2019, IE11, Safari)
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js

function getComputedStyle(element) {
  return getWindow(element).getComputedStyle(element);
}
;// ./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js

function isScrollParent(element) {
  // Firefox wants us to check `-x` and `-y` variations as well
  var _getComputedStyle = getComputedStyle(element),
      overflow = _getComputedStyle.overflow,
      overflowX = _getComputedStyle.overflowX,
      overflowY = _getComputedStyle.overflowY;

  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js









function isElementScaled(element) {
  var rect = element.getBoundingClientRect();
  var scaleX = round(rect.width) / element.offsetWidth || 1;
  var scaleY = round(rect.height) / element.offsetHeight || 1;
  return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.


function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }

  var isOffsetParentAnElement = isHTMLElement(offsetParent);
  var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
  var documentElement = getDocumentElement(offsetParent);
  var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };

  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
    isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }

    if (isHTMLElement(offsetParent)) {
      offsets = getBoundingClientRect(offsetParent, true);
      offsets.x += offsetParent.clientLeft;
      offsets.y += offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }

  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
 // Returns the layout rect of an element relative to its offsetParent. Layout
// means it doesn't take into account transforms.

function getLayoutRect(element) {
  var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
  // Fixes https://github.com/popperjs/popper-core/issues/1223

  var width = element.offsetWidth;
  var height = element.offsetHeight;

  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }

  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }

  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width: width,
    height: height
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js



function getParentNode(element) {
  if (getNodeName(element) === 'html') {
    return element;
  }

  return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
    // $FlowFixMe[incompatible-return]
    // $FlowFixMe[prop-missing]
    element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
    element.parentNode || ( // DOM Element detected
    isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
    // $FlowFixMe[incompatible-call]: HTMLElement is a Node
    getDocumentElement(element) // fallback

  );
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js




function getScrollParent(node) {
  if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
    // $FlowFixMe[incompatible-return]: assume body is always available
    return node.ownerDocument.body;
  }

  if (isHTMLElement(node) && isScrollParent(node)) {
    return node;
  }

  return getScrollParent(getParentNode(node));
}
;// ./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js




/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/

function listScrollParents(element, list) {
  var _element$ownerDocumen;

  if (list === void 0) {
    list = [];
  }

  var scrollParent = getScrollParent(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list.concat(target);
  return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
  updatedList.concat(listScrollParents(getParentNode(target)));
}
;// ./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js

function isTableElement(element) {
  return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js








function getTrueOffsetParent(element) {
  if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
  getComputedStyle(element).position === 'fixed') {
    return null;
  }

  return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block


function getContainingBlock(element) {
  var isFirefox = /firefox/i.test(getUAString());
  var isIE = /Trident/i.test(getUAString());

  if (isIE && isHTMLElement(element)) {
    // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
    var elementCss = getComputedStyle(element);

    if (elementCss.position === 'fixed') {
      return null;
    }
  }

  var currentNode = getParentNode(element);

  if (isShadowRoot(currentNode)) {
    currentNode = currentNode.host;
  }

  while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
    var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that
    // create a containing block.
    // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block

    if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }

  return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.


function getOffsetParent(element) {
  var window = getWindow(element);
  var offsetParent = getTrueOffsetParent(element);

  while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {
    offsetParent = getTrueOffsetParent(offsetParent);
  }

  if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {
    return window;
  }

  return offsetParent || getContainingBlock(element) || window;
}
;// ./node_modules/@popperjs/core/lib/enums.js
var enums_top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var auto = 'auto';
var basePlacements = [enums_top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
  return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var enums_placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
  return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM

var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers

var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)

var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
;// ./node_modules/@popperjs/core/lib/utils/orderModifiers.js
 // source: https://stackoverflow.com/questions/49875255

function order(modifiers) {
  var map = new Map();
  var visited = new Set();
  var result = [];
  modifiers.forEach(function (modifier) {
    map.set(modifier.name, modifier);
  }); // On visiting object, check for its dependencies and visit them recursively

  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function (dep) {
      if (!visited.has(dep)) {
        var depModifier = map.get(dep);

        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result.push(modifier);
  }

  modifiers.forEach(function (modifier) {
    if (!visited.has(modifier.name)) {
      // check for visited object
      sort(modifier);
    }
  });
  return result;
}

function orderModifiers(modifiers) {
  // order based on dependencies
  var orderedModifiers = order(modifiers); // order based on phase

  return modifierPhases.reduce(function (acc, phase) {
    return acc.concat(orderedModifiers.filter(function (modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}
;// ./node_modules/@popperjs/core/lib/utils/debounce.js
function debounce(fn) {
  var pending;
  return function () {
    if (!pending) {
      pending = new Promise(function (resolve) {
        Promise.resolve().then(function () {
          pending = undefined;
          resolve(fn());
        });
      });
    }

    return pending;
  };
}
;// ./node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName(modifiers) {
  var merged = modifiers.reduce(function (merged, current) {
    var existing = merged[current.name];
    merged[current.name] = existing ? Object.assign({}, existing, current, {
      options: Object.assign({}, existing.options, current.options),
      data: Object.assign({}, existing.data, current.data)
    }) : current;
    return merged;
  }, {}); // IE11 does not support Object.values

  return Object.keys(merged).map(function (key) {
    return merged[key];
  });
}
;// ./node_modules/@popperjs/core/lib/createPopper.js









var DEFAULT_OPTIONS = {
  placement: 'bottom',
  modifiers: [],
  strategy: 'absolute'
};

function areValidElements() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return !args.some(function (element) {
    return !(element && typeof element.getBoundingClientRect === 'function');
  });
}

function popperGenerator(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }

  var _generatorOptions = generatorOptions,
      _generatorOptions$def = _generatorOptions.defaultModifiers,
      defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
      _generatorOptions$def2 = _generatorOptions.defaultOptions,
      defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  return function createPopper(reference, popper, options) {
    if (options === void 0) {
      options = defaultOptions;
    }

    var state = {
      placement: 'bottom',
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
      modifiersData: {},
      elements: {
        reference: reference,
        popper: popper
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed = false;
    var instance = {
      state: state,
      setOptions: function setOptions(setOptionsAction) {
        var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions, state.options, options);
        state.scrollParents = {
          reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
          popper: listScrollParents(popper)
        }; // Orders the modifiers based on their dependencies and `phase`
        // properties

        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers

        state.orderedModifiers = orderedModifiers.filter(function (m) {
          return m.enabled;
        });
        runModifierEffects();
        return instance.update();
      },
      // Sync update – it will always be executed, even if not necessary. This
      // is useful for low frequency updates where sync behavior simplifies the
      // logic.
      // For high frequency updates (e.g. `resize` and `scroll` events), always
      // prefer the async Popper#update method
      forceUpdate: function forceUpdate() {
        if (isDestroyed) {
          return;
        }

        var _state$elements = state.elements,
            reference = _state$elements.reference,
            popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
        // anymore

        if (!areValidElements(reference, popper)) {
          return;
        } // Store the reference and popper rects to be read by modifiers


        state.rects = {
          reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
          popper: getLayoutRect(popper)
        }; // Modifiers have the ability to reset the current update cycle. The
        // most common use case for this is the `flip` modifier changing the
        // placement, which then needs to re-run all the modifiers, because the
        // logic was previously ran for the previous placement and is therefore
        // stale/incorrect

        state.reset = false;
        state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
        // is filled with the initial data specified by the modifier. This means
        // it doesn't persist and is fresh on each update.
        // To ensure persistent data, use `${name}#persistent`

        state.orderedModifiers.forEach(function (modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });

        for (var index = 0; index < state.orderedModifiers.length; index++) {
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }

          var _state$orderedModifie = state.orderedModifiers[index],
              fn = _state$orderedModifie.fn,
              _state$orderedModifie2 = _state$orderedModifie.options,
              _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
              name = _state$orderedModifie.name;

          if (typeof fn === 'function') {
            state = fn({
              state: state,
              options: _options,
              name: name,
              instance: instance
            }) || state;
          }
        }
      },
      // Async and optimistically optimized update – it will not be executed if
      // not necessary (debounced to run at most once-per-tick)
      update: debounce(function () {
        return new Promise(function (resolve) {
          instance.forceUpdate();
          resolve(state);
        });
      }),
      destroy: function destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };

    if (!areValidElements(reference, popper)) {
      return instance;
    }

    instance.setOptions(options).then(function (state) {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state);
      }
    }); // Modifiers have the ability to execute arbitrary code before the first
    // update cycle runs. They will be executed in the same order as the update
    // cycle. This is useful when a modifier adds some persistent data that
    // other modifiers need to use, but the modifier is run after the dependent
    // one.

    function runModifierEffects() {
      state.orderedModifiers.forEach(function (_ref) {
        var name = _ref.name,
            _ref$options = _ref.options,
            options = _ref$options === void 0 ? {} : _ref$options,
            effect = _ref.effect;

        if (typeof effect === 'function') {
          var cleanupFn = effect({
            state: state,
            name: name,
            instance: instance,
            options: options
          });

          var noopFn = function noopFn() {};

          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }

    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function (fn) {
        return fn();
      });
      effectCleanupFns = [];
    }

    return instance;
  };
}
var createPopper = /*#__PURE__*/(/* unused pure expression or super */ null && (popperGenerator())); // eslint-disable-next-line import/no-unused-modules


;// ./node_modules/@popperjs/core/lib/modifiers/eventListeners.js
 // eslint-disable-next-line import/no-unused-modules

var passive = {
  passive: true
};

function effect(_ref) {
  var state = _ref.state,
      instance = _ref.instance,
      options = _ref.options;
  var _options$scroll = options.scroll,
      scroll = _options$scroll === void 0 ? true : _options$scroll,
      _options$resize = options.resize,
      resize = _options$resize === void 0 ? true : _options$resize;
  var window = getWindow(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);

  if (scroll) {
    scrollParents.forEach(function (scrollParent) {
      scrollParent.addEventListener('scroll', instance.update, passive);
    });
  }

  if (resize) {
    window.addEventListener('resize', instance.update, passive);
  }

  return function () {
    if (scroll) {
      scrollParents.forEach(function (scrollParent) {
        scrollParent.removeEventListener('scroll', instance.update, passive);
      });
    }

    if (resize) {
      window.removeEventListener('resize', instance.update, passive);
    }
  };
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var eventListeners = ({
  name: 'eventListeners',
  enabled: true,
  phase: 'write',
  fn: function fn() {},
  effect: effect,
  data: {}
});
;// ./node_modules/@popperjs/core/lib/utils/getBasePlacement.js

function getBasePlacement(placement) {
  return placement.split('-')[0];
}
;// ./node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation(placement) {
  return placement.split('-')[1];
}
;// ./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
function getMainAxisFromPlacement(placement) {
  return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}
;// ./node_modules/@popperjs/core/lib/utils/computeOffsets.js




function computeOffsets(_ref) {
  var reference = _ref.reference,
      element = _ref.element,
      placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement(placement) : null;
  var variation = placement ? getVariation(placement) : null;
  var commonX = reference.x + reference.width / 2 - element.width / 2;
  var commonY = reference.y + reference.height / 2 - element.height / 2;
  var offsets;

  switch (basePlacement) {
    case enums_top:
      offsets = {
        x: commonX,
        y: reference.y - element.height
      };
      break;

    case bottom:
      offsets = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;

    case right:
      offsets = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;

    case left:
      offsets = {
        x: reference.x - element.width,
        y: commonY
      };
      break;

    default:
      offsets = {
        x: reference.x,
        y: reference.y
      };
  }

  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;

  if (mainAxis != null) {
    var len = mainAxis === 'y' ? 'height' : 'width';

    switch (variation) {
      case start:
        offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
        break;

      case end:
        offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
        break;

      default:
    }
  }

  return offsets;
}
;// ./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js


function popperOffsets(_ref) {
  var state = _ref.state,
      name = _ref.name;
  // Offsets are the actual position the popper needs to have to be
  // properly positioned near its reference element
  // This is the most basic placement, and will be adjusted by
  // the modifiers in the next step
  state.modifiersData[name] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: 'absolute',
    placement: state.placement
  });
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_popperOffsets = ({
  name: 'popperOffsets',
  enabled: true,
  phase: 'read',
  fn: popperOffsets,
  data: {}
});
;// ./node_modules/@popperjs/core/lib/modifiers/computeStyles.js







 // eslint-disable-next-line import/no-unused-modules

var unsetSides = {
  top: 'auto',
  right: 'auto',
  bottom: 'auto',
  left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.

function roundOffsetsByDPR(_ref, win) {
  var x = _ref.x,
      y = _ref.y;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round(x * dpr) / dpr || 0,
    y: round(y * dpr) / dpr || 0
  };
}

function mapToStyles(_ref2) {
  var _Object$assign2;

  var popper = _ref2.popper,
      popperRect = _ref2.popperRect,
      placement = _ref2.placement,
      variation = _ref2.variation,
      offsets = _ref2.offsets,
      position = _ref2.position,
      gpuAcceleration = _ref2.gpuAcceleration,
      adaptive = _ref2.adaptive,
      roundOffsets = _ref2.roundOffsets,
      isFixed = _ref2.isFixed;
  var _offsets$x = offsets.x,
      x = _offsets$x === void 0 ? 0 : _offsets$x,
      _offsets$y = offsets.y,
      y = _offsets$y === void 0 ? 0 : _offsets$y;

  var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
    x: x,
    y: y
  }) : {
    x: x,
    y: y
  };

  x = _ref3.x;
  y = _ref3.y;
  var hasX = offsets.hasOwnProperty('x');
  var hasY = offsets.hasOwnProperty('y');
  var sideX = left;
  var sideY = enums_top;
  var win = window;

  if (adaptive) {
    var offsetParent = getOffsetParent(popper);
    var heightProp = 'clientHeight';
    var widthProp = 'clientWidth';

    if (offsetParent === getWindow(popper)) {
      offsetParent = getDocumentElement(popper);

      if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {
        heightProp = 'scrollHeight';
        widthProp = 'scrollWidth';
      }
    } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it


    offsetParent = offsetParent;

    if (placement === enums_top || (placement === left || placement === right) && variation === end) {
      sideY = bottom;
      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]
      offsetParent[heightProp];
      y -= offsetY - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }

    if (placement === left || (placement === enums_top || placement === bottom) && variation === end) {
      sideX = right;
      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]
      offsetParent[widthProp];
      x -= offsetX - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }

  var commonStyles = Object.assign({
    position: position
  }, adaptive && unsetSides);

  var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
    x: x,
    y: y
  }, getWindow(popper)) : {
    x: x,
    y: y
  };

  x = _ref4.x;
  y = _ref4.y;

  if (gpuAcceleration) {
    var _Object$assign;

    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }

  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}

function computeStyles(_ref5) {
  var state = _ref5.state,
      options = _ref5.options;
  var _options$gpuAccelerat = options.gpuAcceleration,
      gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
      _options$adaptive = options.adaptive,
      adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
      _options$roundOffsets = options.roundOffsets,
      roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  var commonStyles = {
    placement: getBasePlacement(state.placement),
    variation: getVariation(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration: gpuAcceleration,
    isFixed: state.options.strategy === 'fixed'
  };

  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive: adaptive,
      roundOffsets: roundOffsets
    })));
  }

  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: 'absolute',
      adaptive: false,
      roundOffsets: roundOffsets
    })));
  }

  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-placement': state.placement
  });
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_computeStyles = ({
  name: 'computeStyles',
  enabled: true,
  phase: 'beforeWrite',
  fn: computeStyles,
  data: {}
});
;// ./node_modules/@popperjs/core/lib/modifiers/applyStyles.js

 // This modifier takes the styles prepared by the `computeStyles` modifier
// and applies them to the HTMLElements such as popper and arrow

function applyStyles(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function (name) {
    var style = state.styles[name] || {};
    var attributes = state.attributes[name] || {};
    var element = state.elements[name]; // arrow is optional + virtual elements

    if (!isHTMLElement(element) || !getNodeName(element)) {
      return;
    } // Flow doesn't support to extend this property, but it's the most
    // effective way to apply styles to an HTMLElement
    // $FlowFixMe[cannot-write]


    Object.assign(element.style, style);
    Object.keys(attributes).forEach(function (name) {
      var value = attributes[name];

      if (value === false) {
        element.removeAttribute(name);
      } else {
        element.setAttribute(name, value === true ? '' : value);
      }
    });
  });
}

function applyStyles_effect(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: '0',
      top: '0',
      margin: '0'
    },
    arrow: {
      position: 'absolute'
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;

  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }

  return function () {
    Object.keys(state.elements).forEach(function (name) {
      var element = state.elements[name];
      var attributes = state.attributes[name] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them

      var style = styleProperties.reduce(function (style, property) {
        style[property] = '';
        return style;
      }, {}); // arrow is optional + virtual elements

      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }

      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function (attribute) {
        element.removeAttribute(attribute);
      });
    });
  };
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_applyStyles = ({
  name: 'applyStyles',
  enabled: true,
  phase: 'write',
  fn: applyStyles,
  effect: applyStyles_effect,
  requires: ['computeStyles']
});
;// ./node_modules/@popperjs/core/lib/modifiers/offset.js

 // eslint-disable-next-line import/no-unused-modules

function distanceAndSkiddingToXY(placement, rects, offset) {
  var basePlacement = getBasePlacement(placement);
  var invertDistance = [left, enums_top].indexOf(basePlacement) >= 0 ? -1 : 1;

  var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
    placement: placement
  })) : offset,
      skidding = _ref[0],
      distance = _ref[1];

  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left, right].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}

function offset(_ref2) {
  var state = _ref2.state,
      options = _ref2.options,
      name = _ref2.name;
  var _options$offset = options.offset,
      offset = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data = enums_placements.reduce(function (acc, placement) {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
    return acc;
  }, {});
  var _data$state$placement = data[state.placement],
      x = _data$state$placement.x,
      y = _data$state$placement.y;

  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }

  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_offset = ({
  name: 'offset',
  enabled: true,
  phase: 'main',
  requires: ['popperOffsets'],
  fn: offset
});
;// ./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js
var hash = {
  left: 'right',
  right: 'left',
  bottom: 'top',
  top: 'bottom'
};
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, function (matched) {
    return hash[matched];
  });
}
;// ./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js
var getOppositeVariationPlacement_hash = {
  start: 'end',
  end: 'start'
};
function getOppositeVariationPlacement(placement) {
  return placement.replace(/start|end/g, function (matched) {
    return getOppositeVariationPlacement_hash[matched];
  });
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js




function getViewportRect(element, strategy) {
  var win = getWindow(element);
  var html = getDocumentElement(element);
  var visualViewport = win.visualViewport;
  var width = html.clientWidth;
  var height = html.clientHeight;
  var x = 0;
  var y = 0;

  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    var layoutViewport = isLayoutViewport();

    if (layoutViewport || !layoutViewport && strategy === 'fixed') {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }

  return {
    width: width,
    height: height,
    x: x + getWindowScrollBarX(element),
    y: y
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js




 // Gets the entire size of the scrollable document area, even extending outside
// of the `<html>` and `<body>` rect bounds if horizontally scrollable

function getDocumentRect(element) {
  var _element$ownerDocumen;

  var html = getDocumentElement(element);
  var winScroll = getWindowScroll(element);
  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  var width = math_max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  var height = math_max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  var y = -winScroll.scrollTop;

  if (getComputedStyle(body || html).direction === 'rtl') {
    x += math_max(html.clientWidth, body ? body.clientWidth : 0) - width;
  }

  return {
    width: width,
    height: height,
    x: x,
    y: y
  };
}
;// ./node_modules/@popperjs/core/lib/dom-utils/contains.js

function contains(parent, child) {
  var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method

  if (parent.contains(child)) {
    return true;
  } // then fallback to custom implementation with Shadow DOM support
  else if (rootNode && isShadowRoot(rootNode)) {
      var next = child;

      do {
        if (next && parent.isSameNode(next)) {
          return true;
        } // $FlowFixMe[prop-missing]: need a better way to handle this...


        next = next.parentNode || next.host;
      } while (next);
    } // Give up, the result is false


  return false;
}
;// ./node_modules/@popperjs/core/lib/utils/rectToClientRect.js
function rectToClientRect(rect) {
  return Object.assign({}, rect, {
    left: rect.x,
    top: rect.y,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  });
}
;// ./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js















function getInnerBoundingClientRect(element, strategy) {
  var rect = getBoundingClientRect(element, false, strategy === 'fixed');
  rect.top = rect.top + element.clientTop;
  rect.left = rect.left + element.clientLeft;
  rect.bottom = rect.top + element.clientHeight;
  rect.right = rect.left + element.clientWidth;
  rect.width = element.clientWidth;
  rect.height = element.clientHeight;
  rect.x = rect.left;
  rect.y = rect.top;
  return rect;
}

function getClientRectFromMixedType(element, clippingParent, strategy) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`


function getClippingParents(element) {
  var clippingParents = listScrollParents(getParentNode(element));
  var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;
  var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;

  if (!isElement(clipperElement)) {
    return [];
  } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414


  return clippingParents.filter(function (clippingParent) {
    return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
  });
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents


function getClippingRect(element, boundary, rootBoundary, strategy) {
  var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
  var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
  var firstClippingParent = clippingParents[0];
  var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
    var rect = getClientRectFromMixedType(element, clippingParent, strategy);
    accRect.top = math_max(rect.top, accRect.top);
    accRect.right = math_min(rect.right, accRect.right);
    accRect.bottom = math_min(rect.bottom, accRect.bottom);
    accRect.left = math_max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromMixedType(element, firstClippingParent, strategy));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}
;// ./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js
function getFreshSideObject() {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
}
;// ./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js

function mergePaddingObject(paddingObject) {
  return Object.assign({}, getFreshSideObject(), paddingObject);
}
;// ./node_modules/@popperjs/core/lib/utils/expandToHashMap.js
function expandToHashMap(value, keys) {
  return keys.reduce(function (hashMap, key) {
    hashMap[key] = value;
    return hashMap;
  }, {});
}
;// ./node_modules/@popperjs/core/lib/utils/detectOverflow.js








 // eslint-disable-next-line import/no-unused-modules

function detectOverflow(state, options) {
  if (options === void 0) {
    options = {};
  }

  var _options = options,
      _options$placement = _options.placement,
      placement = _options$placement === void 0 ? state.placement : _options$placement,
      _options$strategy = _options.strategy,
      strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
      _options$boundary = _options.boundary,
      boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
      _options$rootBoundary = _options.rootBoundary,
      rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
      _options$elementConte = _options.elementContext,
      elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
      _options$altBoundary = _options.altBoundary,
      altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
      _options$padding = _options.padding,
      padding = _options$padding === void 0 ? 0 : _options$padding;
  var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
  var altContext = elementContext === popper ? reference : popper;
  var popperRect = state.rects.popper;
  var element = state.elements[altBoundary ? altContext : elementContext];
  var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
  var referenceClientRect = getBoundingClientRect(state.elements.reference);
  var popperOffsets = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    strategy: 'absolute',
    placement: placement
  });
  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
  var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
  // 0 or negative = within the clipping rect

  var overflowOffsets = {
    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
    right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  };
  var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element

  if (elementContext === popper && offsetData) {
    var offset = offsetData[placement];
    Object.keys(overflowOffsets).forEach(function (key) {
      var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
      var axis = [enums_top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
      overflowOffsets[key] += offset[axis] * multiply;
    });
  }

  return overflowOffsets;
}
;// ./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js




function computeAutoPlacement(state, options) {
  if (options === void 0) {
    options = {};
  }

  var _options = options,
      placement = _options.placement,
      boundary = _options.boundary,
      rootBoundary = _options.rootBoundary,
      padding = _options.padding,
      flipVariations = _options.flipVariations,
      _options$allowedAutoP = _options.allowedAutoPlacements,
      allowedAutoPlacements = _options$allowedAutoP === void 0 ? enums_placements : _options$allowedAutoP;
  var variation = getVariation(placement);
  var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
    return getVariation(placement) === variation;
  }) : basePlacements;
  var allowedPlacements = placements.filter(function (placement) {
    return allowedAutoPlacements.indexOf(placement) >= 0;
  });

  if (allowedPlacements.length === 0) {
    allowedPlacements = placements;
  } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...


  var overflows = allowedPlacements.reduce(function (acc, placement) {
    acc[placement] = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding
    })[getBasePlacement(placement)];
    return acc;
  }, {});
  return Object.keys(overflows).sort(function (a, b) {
    return overflows[a] - overflows[b];
  });
}
;// ./node_modules/@popperjs/core/lib/modifiers/flip.js






 // eslint-disable-next-line import/no-unused-modules

function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement(placement) === auto) {
    return [];
  }

  var oppositePlacement = getOppositePlacement(placement);
  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}

function flip(_ref) {
  var state = _ref.state,
      options = _ref.options,
      name = _ref.name;

  if (state.modifiersData[name]._skip) {
    return;
  }

  var _options$mainAxis = options.mainAxis,
      checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
      _options$altAxis = options.altAxis,
      checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
      specifiedFallbackPlacements = options.fallbackPlacements,
      padding = options.padding,
      boundary = options.boundary,
      rootBoundary = options.rootBoundary,
      altBoundary = options.altBoundary,
      _options$flipVariatio = options.flipVariations,
      flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
      allowedAutoPlacements = options.allowedAutoPlacements;
  var preferredPlacement = state.options.placement;
  var basePlacement = getBasePlacement(preferredPlacement);
  var isBasePlacement = basePlacement === preferredPlacement;
  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
    return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding,
      flipVariations: flipVariations,
      allowedAutoPlacements: allowedAutoPlacements
    }) : placement);
  }, []);
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var checksMap = new Map();
  var makeFallbackChecks = true;
  var firstFittingPlacement = placements[0];

  for (var i = 0; i < placements.length; i++) {
    var placement = placements[i];

    var _basePlacement = getBasePlacement(placement);

    var isStartVariation = getVariation(placement) === start;
    var isVertical = [enums_top, bottom].indexOf(_basePlacement) >= 0;
    var len = isVertical ? 'width' : 'height';
    var overflow = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      altBoundary: altBoundary,
      padding: padding
    });
    var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : enums_top;

    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }

    var altVariationSide = getOppositePlacement(mainVariationSide);
    var checks = [];

    if (checkMainAxis) {
      checks.push(overflow[_basePlacement] <= 0);
    }

    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }

    if (checks.every(function (check) {
      return check;
    })) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }

    checksMap.set(placement, checks);
  }

  if (makeFallbackChecks) {
    // `2` may be desired in some cases – research later
    var numberOfChecks = flipVariations ? 3 : 1;

    var _loop = function _loop(_i) {
      var fittingPlacement = placements.find(function (placement) {
        var checks = checksMap.get(placement);

        if (checks) {
          return checks.slice(0, _i).every(function (check) {
            return check;
          });
        }
      });

      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        return "break";
      }
    };

    for (var _i = numberOfChecks; _i > 0; _i--) {
      var _ret = _loop(_i);

      if (_ret === "break") break;
    }
  }

  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_flip = ({
  name: 'flip',
  enabled: true,
  phase: 'main',
  fn: flip,
  requiresIfExists: ['offset'],
  data: {
    _skip: false
  }
});
;// ./node_modules/@popperjs/core/lib/utils/getAltAxis.js
function getAltAxis(axis) {
  return axis === 'x' ? 'y' : 'x';
}
;// ./node_modules/@popperjs/core/lib/utils/within.js

function within(min, value, max) {
  return math_max(min, math_min(value, max));
}
function withinMaxClamp(min, value, max) {
  var v = within(min, value, max);
  return v > max ? max : v;
}
;// ./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js












function preventOverflow(_ref) {
  var state = _ref.state,
      options = _ref.options,
      name = _ref.name;
  var _options$mainAxis = options.mainAxis,
      checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
      _options$altAxis = options.altAxis,
      checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
      boundary = options.boundary,
      rootBoundary = options.rootBoundary,
      altBoundary = options.altBoundary,
      padding = options.padding,
      _options$tether = options.tether,
      tether = _options$tether === void 0 ? true : _options$tether,
      _options$tetherOffset = options.tetherOffset,
      tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  var overflow = detectOverflow(state, {
    boundary: boundary,
    rootBoundary: rootBoundary,
    padding: padding,
    altBoundary: altBoundary
  });
  var basePlacement = getBasePlacement(state.placement);
  var variation = getVariation(state.placement);
  var isBasePlacement = !variation;
  var mainAxis = getMainAxisFromPlacement(basePlacement);
  var altAxis = getAltAxis(mainAxis);
  var popperOffsets = state.modifiersData.popperOffsets;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
    placement: state.placement
  })) : tetherOffset;
  var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
    mainAxis: tetherOffsetValue,
    altAxis: tetherOffsetValue
  } : Object.assign({
    mainAxis: 0,
    altAxis: 0
  }, tetherOffsetValue);
  var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
  var data = {
    x: 0,
    y: 0
  };

  if (!popperOffsets) {
    return;
  }

  if (checkMainAxis) {
    var _offsetModifierState$;

    var mainSide = mainAxis === 'y' ? enums_top : left;
    var altSide = mainAxis === 'y' ? bottom : right;
    var len = mainAxis === 'y' ? 'height' : 'width';
    var offset = popperOffsets[mainAxis];
    var min = offset + overflow[mainSide];
    var max = offset - overflow[altSide];
    var additive = tether ? -popperRect[len] / 2 : 0;
    var minLen = variation === start ? referenceRect[len] : popperRect[len];
    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
    // outside the reference bounds

    var arrowElement = state.elements.arrow;
    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
      width: 0,
      height: 0
    };
    var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
    var arrowPaddingMin = arrowPaddingObject[mainSide];
    var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
    // to include its full size in the calculation. If the reference is small
    // and near the edge of a boundary, the popper can overflow even if the
    // reference is not overflowing as well (e.g. virtual elements with no
    // width or height)

    var arrowLen = within(0, referenceRect[len], arrowRect[len]);
    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
    var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
    var tetherMax = offset + maxOffset - offsetModifierValue;
    var preventedOffset = within(tether ? math_min(min, tetherMin) : min, offset, tether ? math_max(max, tetherMax) : max);
    popperOffsets[mainAxis] = preventedOffset;
    data[mainAxis] = preventedOffset - offset;
  }

  if (checkAltAxis) {
    var _offsetModifierState$2;

    var _mainSide = mainAxis === 'x' ? enums_top : left;

    var _altSide = mainAxis === 'x' ? bottom : right;

    var _offset = popperOffsets[altAxis];

    var _len = altAxis === 'y' ? 'height' : 'width';

    var _min = _offset + overflow[_mainSide];

    var _max = _offset - overflow[_altSide];

    var isOriginSide = [enums_top, left].indexOf(basePlacement) !== -1;

    var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;

    var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;

    var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;

    var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);

    popperOffsets[altAxis] = _preventedOffset;
    data[altAxis] = _preventedOffset - _offset;
  }

  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_preventOverflow = ({
  name: 'preventOverflow',
  enabled: true,
  phase: 'main',
  fn: preventOverflow,
  requiresIfExists: ['offset']
});
;// ./node_modules/@popperjs/core/lib/modifiers/arrow.js








 // eslint-disable-next-line import/no-unused-modules

var toPaddingObject = function toPaddingObject(padding, state) {
  padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
    placement: state.placement
  })) : padding;
  return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};

function arrow(_ref) {
  var _state$modifiersData$;

  var state = _ref.state,
      name = _ref.name,
      options = _ref.options;
  var arrowElement = state.elements.arrow;
  var popperOffsets = state.modifiersData.popperOffsets;
  var basePlacement = getBasePlacement(state.placement);
  var axis = getMainAxisFromPlacement(basePlacement);
  var isVertical = [left, right].indexOf(basePlacement) >= 0;
  var len = isVertical ? 'height' : 'width';

  if (!arrowElement || !popperOffsets) {
    return;
  }

  var paddingObject = toPaddingObject(options.padding, state);
  var arrowRect = getLayoutRect(arrowElement);
  var minProp = axis === 'y' ? enums_top : left;
  var maxProp = axis === 'y' ? bottom : right;
  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
  var startDiff = popperOffsets[axis] - state.rects.reference[axis];
  var arrowOffsetParent = getOffsetParent(arrowElement);
  var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
  // outside of the popper bounds

  var min = paddingObject[minProp];
  var max = clientSize - arrowRect[len] - paddingObject[maxProp];
  var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  var offset = within(min, center, max); // Prevents breaking syntax highlighting...

  var axisProp = axis;
  state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}

function arrow_effect(_ref2) {
  var state = _ref2.state,
      options = _ref2.options;
  var _options$element = options.element,
      arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;

  if (arrowElement == null) {
    return;
  } // CSS selector


  if (typeof arrowElement === 'string') {
    arrowElement = state.elements.popper.querySelector(arrowElement);

    if (!arrowElement) {
      return;
    }
  }

  if (!contains(state.elements.popper, arrowElement)) {
    return;
  }

  state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_arrow = ({
  name: 'arrow',
  enabled: true,
  phase: 'main',
  fn: arrow,
  effect: arrow_effect,
  requires: ['popperOffsets'],
  requiresIfExists: ['preventOverflow']
});
;// ./node_modules/@popperjs/core/lib/modifiers/hide.js



function getSideOffsets(overflow, rect, preventedOffsets) {
  if (preventedOffsets === void 0) {
    preventedOffsets = {
      x: 0,
      y: 0
    };
  }

  return {
    top: overflow.top - rect.height - preventedOffsets.y,
    right: overflow.right - rect.width + preventedOffsets.x,
    bottom: overflow.bottom - rect.height + preventedOffsets.y,
    left: overflow.left - rect.width - preventedOffsets.x
  };
}

function isAnySideFullyClipped(overflow) {
  return [enums_top, right, bottom, left].some(function (side) {
    return overflow[side] >= 0;
  });
}

function hide(_ref) {
  var state = _ref.state,
      name = _ref.name;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var preventedOffsets = state.modifiersData.preventOverflow;
  var referenceOverflow = detectOverflow(state, {
    elementContext: 'reference'
  });
  var popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name] = {
    referenceClippingOffsets: referenceClippingOffsets,
    popperEscapeOffsets: popperEscapeOffsets,
    isReferenceHidden: isReferenceHidden,
    hasPopperEscaped: hasPopperEscaped
  };
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-reference-hidden': isReferenceHidden,
    'data-popper-escaped': hasPopperEscaped
  });
} // eslint-disable-next-line import/no-unused-modules


/* harmony default export */ var modifiers_hide = ({
  name: 'hide',
  enabled: true,
  phase: 'main',
  requiresIfExists: ['preventOverflow'],
  fn: hide
});
;// ./node_modules/@popperjs/core/lib/popper.js










var defaultModifiers = [eventListeners, modifiers_popperOffsets, modifiers_computeStyles, modifiers_applyStyles, modifiers_offset, modifiers_flip, modifiers_preventOverflow, modifiers_arrow, modifiers_hide];
var popper_createPopper = /*#__PURE__*/popperGenerator({
  defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules

 // eslint-disable-next-line import/no-unused-modules

 // eslint-disable-next-line import/no-unused-modules



/***/ }),

/***/ 5540:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  A: function() { return /* binding */ _inheritsLoose; }
});

;// ./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
function _setPrototypeOf(t, e) {
  return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
    return t.__proto__ = e, t;
  }, _setPrototypeOf(t, e);
}

;// ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js

function _inheritsLoose(t, o) {
  t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
}


/***/ }),

/***/ 5588:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Gh: function() { return /* binding */ resolveTo; },
/* harmony export */   HS: function() { return /* binding */ joinPaths; },
/* harmony export */   Oi: function() { return /* binding */ invariant; },
/* harmony export */   Rr: function() { return /* binding */ parsePath; },
/* harmony export */   TM: function() { return /* binding */ createHashHistory; },
/* harmony export */   pX: function() { return /* binding */ isRouteErrorResponse; },
/* harmony export */   pb: function() { return /* binding */ stripBasename; },
/* harmony export */   rc: function() { return /* binding */ Action; },
/* harmony export */   tH: function() { return /* binding */ AbortedDeferredError; },
/* harmony export */   ue: function() { return /* binding */ matchRoutes; },
/* harmony export */   yD: function() { return /* binding */ getResolveToMatches; }
/* harmony export */ });
/* unused harmony exports IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, UNSAFE_DeferredData, UNSAFE_ErrorResponseImpl, UNSAFE_convertRouteMatchToUiMatch, UNSAFE_convertRoutesToDataRoutes, UNSAFE_warning, createBrowserHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, isDeferredData, json, matchPath, normalizePathname, redirect, redirectDocument, resolvePath */
/**
 * @remix-run/router v1.15.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
function _extends() {
  _extends = Object.assign ? Object.assign.bind() : 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);
}

////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////
/**
 * Actions represent the type of change to a location value.
 */
var Action;
(function (Action) {
  /**
   * A POP indicates a change to an arbitrary index in the history stack, such
   * as a back or forward navigation. It does not describe the direction of the
   * navigation, only that the current index changed.
   *
   * Note: This is the default action for newly created history objects.
   */
  Action["Pop"] = "POP";
  /**
   * A PUSH indicates a new entry being added to the history stack, such as when
   * a link is clicked and a new page loads. When this happens, all subsequent
   * entries in the stack are lost.
   */
  Action["Push"] = "PUSH";
  /**
   * A REPLACE indicates the entry at the current index in the history stack
   * being replaced by a new one.
   */
  Action["Replace"] = "REPLACE";
})(Action || (Action = {}));
const PopStateEventType = "popstate";
/**
 * Memory history stores the current location in memory. It is designed for use
 * in stateful non-browser environments like tests and React Native.
 */
function createMemoryHistory(options) {
  if (options === void 0) {
    options = {};
  }
  let {
    initialEntries = ["/"],
    initialIndex,
    v5Compat = false
  } = options;
  let entries; // Declare so we can access from createMemoryLocation
  entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
  let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
  let action = Action.Pop;
  let listener = null;
  function clampIndex(n) {
    return Math.min(Math.max(n, 0), entries.length - 1);
  }
  function getCurrentLocation() {
    return entries[index];
  }
  function createMemoryLocation(to, state, key) {
    if (state === void 0) {
      state = null;
    }
    let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
    warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
    return location;
  }
  function createHref(to) {
    return typeof to === "string" ? to : createPath(to);
  }
  let history = {
    get index() {
      return index;
    },
    get action() {
      return action;
    },
    get location() {
      return getCurrentLocation();
    },
    createHref,
    createURL(to) {
      return new URL(createHref(to), "http://localhost");
    },
    encodeLocation(to) {
      let path = typeof to === "string" ? parsePath(to) : to;
      return {
        pathname: path.pathname || "",
        search: path.search || "",
        hash: path.hash || ""
      };
    },
    push(to, state) {
      action = Action.Push;
      let nextLocation = createMemoryLocation(to, state);
      index += 1;
      entries.splice(index, entries.length, nextLocation);
      if (v5Compat && listener) {
        listener({
          action,
          location: nextLocation,
          delta: 1
        });
      }
    },
    replace(to, state) {
      action = Action.Replace;
      let nextLocation = createMemoryLocation(to, state);
      entries[index] = nextLocation;
      if (v5Compat && listener) {
        listener({
          action,
          location: nextLocation,
          delta: 0
        });
      }
    },
    go(delta) {
      action = Action.Pop;
      let nextIndex = clampIndex(index + delta);
      let nextLocation = entries[nextIndex];
      index = nextIndex;
      if (listener) {
        listener({
          action,
          location: nextLocation,
          delta
        });
      }
    },
    listen(fn) {
      listener = fn;
      return () => {
        listener = null;
      };
    }
  };
  return history;
}
/**
 * Browser history stores the location in regular URLs. This is the standard for
 * most web apps, but it requires some configuration on the server to ensure you
 * serve the same app at multiple URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
 */
function createBrowserHistory(options) {
  if (options === void 0) {
    options = {};
  }
  function createBrowserLocation(window, globalHistory) {
    let {
      pathname,
      search,
      hash
    } = window.location;
    return createLocation("", {
      pathname,
      search,
      hash
    },
    // state defaults to `null` because `window.history.state` does
    globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
  }
  function createBrowserHref(window, to) {
    return typeof to === "string" ? to : createPath(to);
  }
  return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
}
/**
 * Hash history stores the location in window.location.hash. This makes it ideal
 * for situations where you don't want to send the location to the server for
 * some reason, either because you do cannot configure it or the URL space is
 * reserved for something else.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
 */
function createHashHistory(options) {
  if (options === void 0) {
    options = {};
  }
  function createHashLocation(window, globalHistory) {
    let {
      pathname = "/",
      search = "",
      hash = ""
    } = parsePath(window.location.hash.substr(1));
    // Hash URL should always have a leading / just like window.location.pathname
    // does, so if an app ends up at a route like /#something then we add a
    // leading slash so all of our path-matching behaves the same as if it would
    // in a browser router.  This is particularly important when there exists a
    // root splat route (<Route path="*">) since that matches internally against
    // "/*" and we'd expect /#something to 404 in a hash router app.
    if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
      pathname = "/" + pathname;
    }
    return createLocation("", {
      pathname,
      search,
      hash
    },
    // state defaults to `null` because `window.history.state` does
    globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
  }
  function createHashHref(window, to) {
    let base = window.document.querySelector("base");
    let href = "";
    if (base && base.getAttribute("href")) {
      let url = window.location.href;
      let hashIndex = url.indexOf("#");
      href = hashIndex === -1 ? url : url.slice(0, hashIndex);
    }
    return href + "#" + (typeof to === "string" ? to : createPath(to));
  }
  function validateHashLocation(location, to) {
    warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
  }
  return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
}
function invariant(value, message) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message);
  }
}
function warning(cond, message) {
  if (!cond) {
    // eslint-disable-next-line no-console
    if (typeof console !== "undefined") console.warn(message);
    try {
      // Welcome to debugging history!
      //
      // This error is thrown as a convenience, so you can more easily
      // find the source for a warning that appears in the console by
      // enabling "pause on exceptions" in your JavaScript debugger.
      throw new Error(message);
      // eslint-disable-next-line no-empty
    } catch (e) {}
  }
}
function createKey() {
  return Math.random().toString(36).substr(2, 8);
}
/**
 * For browser-based histories, we combine the state and key into an object
 */
function getHistoryState(location, index) {
  return {
    usr: location.state,
    key: location.key,
    idx: index
  };
}
/**
 * Creates a Location object with a unique key from the given Path
 */
function createLocation(current, to, state, key) {
  if (state === void 0) {
    state = null;
  }
  let location = _extends({
    pathname: typeof current === "string" ? current : current.pathname,
    search: "",
    hash: ""
  }, typeof to === "string" ? parsePath(to) : to, {
    state,
    // TODO: This could be cleaned up.  push/replace should probably just take
    // full Locations now and avoid the need to run through this flow at all
    // But that's a pretty big refactor to the current test suite so going to
    // keep as is for the time being and just let any incoming keys take precedence
    key: to && to.key || key || createKey()
  });
  return location;
}
/**
 * Creates a string URL path from the given pathname, search, and hash components.
 */
function createPath(_ref) {
  let {
    pathname = "/",
    search = "",
    hash = ""
  } = _ref;
  if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
  if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  return pathname;
}
/**
 * Parses a string URL path into its separate pathname, search, and hash components.
 */
function parsePath(path) {
  let parsedPath = {};
  if (path) {
    let hashIndex = path.indexOf("#");
    if (hashIndex >= 0) {
      parsedPath.hash = path.substr(hashIndex);
      path = path.substr(0, hashIndex);
    }
    let searchIndex = path.indexOf("?");
    if (searchIndex >= 0) {
      parsedPath.search = path.substr(searchIndex);
      path = path.substr(0, searchIndex);
    }
    if (path) {
      parsedPath.pathname = path;
    }
  }
  return parsedPath;
}
function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
  if (options === void 0) {
    options = {};
  }
  let {
    window = document.defaultView,
    v5Compat = false
  } = options;
  let globalHistory = window.history;
  let action = Action.Pop;
  let listener = null;
  let index = getIndex();
  // Index should only be null when we initialize. If not, it's because the
  // user called history.pushState or history.replaceState directly, in which
  // case we should log a warning as it will result in bugs.
  if (index == null) {
    index = 0;
    globalHistory.replaceState(_extends({}, globalHistory.state, {
      idx: index
    }), "");
  }
  function getIndex() {
    let state = globalHistory.state || {
      idx: null
    };
    return state.idx;
  }
  function handlePop() {
    action = Action.Pop;
    let nextIndex = getIndex();
    let delta = nextIndex == null ? null : nextIndex - index;
    index = nextIndex;
    if (listener) {
      listener({
        action,
        location: history.location,
        delta
      });
    }
  }
  function push(to, state) {
    action = Action.Push;
    let location = createLocation(history.location, to, state);
    if (validateLocation) validateLocation(location, to);
    index = getIndex() + 1;
    let historyState = getHistoryState(location, index);
    let url = history.createHref(location);
    // try...catch because iOS limits us to 100 pushState calls :/
    try {
      globalHistory.pushState(historyState, "", url);
    } catch (error) {
      // If the exception is because `state` can't be serialized, let that throw
      // outwards just like a replace call would so the dev knows the cause
      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
      if (error instanceof DOMException && error.name === "DataCloneError") {
        throw error;
      }
      // They are going to lose state here, but there is no real
      // way to warn them about it since the page will refresh...
      window.location.assign(url);
    }
    if (v5Compat && listener) {
      listener({
        action,
        location: history.location,
        delta: 1
      });
    }
  }
  function replace(to, state) {
    action = Action.Replace;
    let location = createLocation(history.location, to, state);
    if (validateLocation) validateLocation(location, to);
    index = getIndex();
    let historyState = getHistoryState(location, index);
    let url = history.createHref(location);
    globalHistory.replaceState(historyState, "", url);
    if (v5Compat && listener) {
      listener({
        action,
        location: history.location,
        delta: 0
      });
    }
  }
  function createURL(to) {
    // window.location.origin is "null" (the literal string value) in Firefox
    // under certain conditions, notably when serving from a local HTML file
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
    let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
    let href = typeof to === "string" ? to : createPath(to);
    // Treating this as a full URL will strip any trailing spaces so we need to
    // pre-encode them since they might be part of a matching splat param from
    // an ancestor route
    href = href.replace(/ $/, "%20");
    invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
    return new URL(href, base);
  }
  let history = {
    get action() {
      return action;
    },
    get location() {
      return getLocation(window, globalHistory);
    },
    listen(fn) {
      if (listener) {
        throw new Error("A history only accepts one active listener");
      }
      window.addEventListener(PopStateEventType, handlePop);
      listener = fn;
      return () => {
        window.removeEventListener(PopStateEventType, handlePop);
        listener = null;
      };
    },
    createHref(to) {
      return createHref(window, to);
    },
    createURL,
    encodeLocation(to) {
      // Encode a Location the same way window.location would
      let url = createURL(to);
      return {
        pathname: url.pathname,
        search: url.search,
        hash: url.hash
      };
    },
    push,
    replace,
    go(n) {
      return globalHistory.go(n);
    }
  };
  return history;
}
//#endregion

var ResultType;
(function (ResultType) {
  ResultType["data"] = "data";
  ResultType["deferred"] = "deferred";
  ResultType["redirect"] = "redirect";
  ResultType["error"] = "error";
})(ResultType || (ResultType = {}));
const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
function isIndexRoute(route) {
  return route.index === true;
}
// Walk the route tree generating unique IDs where necessary, so we are working
// solely with AgnosticDataRouteObject's within the Router
function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
  if (parentPath === void 0) {
    parentPath = [];
  }
  if (manifest === void 0) {
    manifest = {};
  }
  return routes.map((route, index) => {
    let treePath = [...parentPath, index];
    let id = typeof route.id === "string" ? route.id : treePath.join("-");
    invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
    invariant(!manifest[id], "Found a route id collision on id \"" + id + "\".  Route " + "id's must be globally unique within Data Router usages");
    if (isIndexRoute(route)) {
      let indexRoute = _extends({}, route, mapRouteProperties(route), {
        id
      });
      manifest[id] = indexRoute;
      return indexRoute;
    } else {
      let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {
        id,
        children: undefined
      });
      manifest[id] = pathOrLayoutRoute;
      if (route.children) {
        pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
      }
      return pathOrLayoutRoute;
    }
  });
}
/**
 * Matches the given routes to a location and returns the match data.
 *
 * @see https://reactrouter.com/utils/match-routes
 */
function matchRoutes(routes, locationArg, basename) {
  if (basename === void 0) {
    basename = "/";
  }
  let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  let pathname = stripBasename(location.pathname || "/", basename);
  if (pathname == null) {
    return null;
  }
  let branches = flattenRoutes(routes);
  rankRouteBranches(branches);
  let matches = null;
  for (let i = 0; matches == null && i < branches.length; ++i) {
    // Incoming pathnames are generally encoded from either window.location
    // or from router.navigate, but we want to match against the unencoded
    // paths in the route definitions.  Memory router locations won't be
    // encoded here but there also shouldn't be anything to decode so this
    // should be a safe operation.  This avoids needing matchRoutes to be
    // history-aware.
    let decoded = decodePath(pathname);
    matches = matchRouteBranch(branches[i], decoded);
  }
  return matches;
}
function convertRouteMatchToUiMatch(match, loaderData) {
  let {
    route,
    pathname,
    params
  } = match;
  return {
    id: route.id,
    pathname,
    params,
    data: loaderData[route.id],
    handle: route.handle
  };
}
function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  if (branches === void 0) {
    branches = [];
  }
  if (parentsMeta === void 0) {
    parentsMeta = [];
  }
  if (parentPath === void 0) {
    parentPath = "";
  }
  let flattenRoute = (route, index, relativePath) => {
    let meta = {
      relativePath: relativePath === undefined ? route.path || "" : relativePath,
      caseSensitive: route.caseSensitive === true,
      childrenIndex: index,
      route
    };
    if (meta.relativePath.startsWith("/")) {
      invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes.");
      meta.relativePath = meta.relativePath.slice(parentPath.length);
    }
    let path = joinPaths([parentPath, meta.relativePath]);
    let routesMeta = parentsMeta.concat(meta);
    // Add the children before adding this route to the array, so we traverse the
    // route tree depth-first and child routes appear before their parents in
    // the "flattened" version.
    if (route.children && route.children.length > 0) {
      invariant(
      // Our types know better, but runtime JS may not!
      // @ts-expect-error
      route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
      flattenRoutes(route.children, branches, routesMeta, path);
    }
    // Routes without a path shouldn't ever match by themselves unless they are
    // index routes, so don't add them to the list of possible branches.
    if (route.path == null && !route.index) {
      return;
    }
    branches.push({
      path,
      score: computeScore(path, route.index),
      routesMeta
    });
  };
  routes.forEach((route, index) => {
    var _route$path;
    // coarse-grain check for optional params
    if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
      flattenRoute(route, index);
    } else {
      for (let exploded of explodeOptionalSegments(route.path)) {
        flattenRoute(route, index, exploded);
      }
    }
  });
  return branches;
}
/**
 * Computes all combinations of optional path segments for a given path,
 * excluding combinations that are ambiguous and of lower priority.
 *
 * For example, `/one/:two?/three/:four?/:five?` explodes to:
 * - `/one/three`
 * - `/one/:two/three`
 * - `/one/three/:four`
 * - `/one/three/:five`
 * - `/one/:two/three/:four`
 * - `/one/:two/three/:five`
 * - `/one/three/:four/:five`
 * - `/one/:two/three/:four/:five`
 */
function explodeOptionalSegments(path) {
  let segments = path.split("/");
  if (segments.length === 0) return [];
  let [first, ...rest] = segments;
  // Optional path segments are denoted by a trailing `?`
  let isOptional = first.endsWith("?");
  // Compute the corresponding required segment: `foo?` -> `foo`
  let required = first.replace(/\?$/, "");
  if (rest.length === 0) {
    // Intepret empty string as omitting an optional segment
    // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
    return isOptional ? [required, ""] : [required];
  }
  let restExploded = explodeOptionalSegments(rest.join("/"));
  let result = [];
  // All child paths with the prefix.  Do this for all children before the
  // optional version for all children, so we get consistent ordering where the
  // parent optional aspect is preferred as required.  Otherwise, we can get
  // child sections interspersed where deeper optional segments are higher than
  // parent optional segments, where for example, /:two would explode _earlier_
  // then /:one.  By always including the parent as required _for all children_
  // first, we avoid this issue
  result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));
  // Then, if this is an optional value, add all child versions without
  if (isOptional) {
    result.push(...restExploded);
  }
  // for absolute paths, ensure `/` instead of empty segment
  return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
}
function rankRouteBranches(branches) {
  branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
  : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
}
const paramRe = /^:[\w-]+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = s => s === "*";
function computeScore(path, index) {
  let segments = path.split("/");
  let initialScore = segments.length;
  if (segments.some(isSplat)) {
    initialScore += splatPenalty;
  }
  if (index) {
    initialScore += indexRouteValue;
  }
  return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a, b) {
  let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  return siblings ?
  // If two routes are siblings, we should try to match the earlier sibling
  // first. This allows people to have fine-grained control over the matching
  // behavior by simply putting routes with identical paths in the order they
  // want them tried.
  a[a.length - 1] - b[b.length - 1] :
  // Otherwise, it doesn't really make sense to rank non-siblings by index,
  // so they sort equally.
  0;
}
function matchRouteBranch(branch, pathname) {
  let {
    routesMeta
  } = branch;
  let matchedParams = {};
  let matchedPathname = "/";
  let matches = [];
  for (let i = 0; i < routesMeta.length; ++i) {
    let meta = routesMeta[i];
    let end = i === routesMeta.length - 1;
    let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
    let match = matchPath({
      path: meta.relativePath,
      caseSensitive: meta.caseSensitive,
      end
    }, remainingPathname);
    if (!match) return null;
    Object.assign(matchedParams, match.params);
    let route = meta.route;
    matches.push({
      // TODO: Can this as be avoided?
      params: matchedParams,
      pathname: joinPaths([matchedPathname, match.pathname]),
      pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
      route
    });
    if (match.pathnameBase !== "/") {
      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
    }
  }
  return matches;
}
/**
 * Returns a path with params interpolated.
 *
 * @see https://reactrouter.com/utils/generate-path
 */
function generatePath(originalPath, params) {
  if (params === void 0) {
    params = {};
  }
  let path = originalPath;
  if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
    warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
    path = path.replace(/\*$/, "/*");
  }
  // ensure `/` is added at the beginning if the path is absolute
  const prefix = path.startsWith("/") ? "/" : "";
  const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p);
  const segments = path.split(/\/+/).map((segment, index, array) => {
    const isLastSegment = index === array.length - 1;
    // only apply the splat if it's the last segment
    if (isLastSegment && segment === "*") {
      const star = "*";
      // Apply the splat
      return stringify(params[star]);
    }
    const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
    if (keyMatch) {
      const [, key, optional] = keyMatch;
      let param = params[key];
      invariant(optional === "?" || param != null, "Missing \":" + key + "\" param");
      return stringify(param);
    }
    // Remove any optional markers from optional static segments
    return segment.replace(/\?$/g, "");
  })
  // Remove empty segments
  .filter(segment => !!segment);
  return prefix + segments.join("/");
}
/**
 * Performs pattern matching on a URL pathname and returns information about
 * the match.
 *
 * @see https://reactrouter.com/utils/match-path
 */
function matchPath(pattern, pathname) {
  if (typeof pattern === "string") {
    pattern = {
      path: pattern,
      caseSensitive: false,
      end: true
    };
  }
  let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
  let match = pathname.match(matcher);
  if (!match) return null;
  let matchedPathname = match[0];
  let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  let captureGroups = match.slice(1);
  let params = compiledParams.reduce((memo, _ref, index) => {
    let {
      paramName,
      isOptional
    } = _ref;
    // We need to compute the pathnameBase here using the raw splat value
    // instead of using params["*"] later because it will be decoded then
    if (paramName === "*") {
      let splatValue = captureGroups[index] || "";
      pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
    }
    const value = captureGroups[index];
    if (isOptional && !value) {
      memo[paramName] = undefined;
    } else {
      memo[paramName] = (value || "").replace(/%2F/g, "/");
    }
    return memo;
  }, {});
  return {
    params,
    pathname: matchedPathname,
    pathnameBase,
    pattern
  };
}
function compilePath(path, caseSensitive, end) {
  if (caseSensitive === void 0) {
    caseSensitive = false;
  }
  if (end === void 0) {
    end = true;
  }
  warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
  let params = [];
  let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
  .replace(/^\/*/, "/") // Make sure it has a leading /
  .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
  .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
    params.push({
      paramName,
      isOptional: isOptional != null
    });
    return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  });
  if (path.endsWith("*")) {
    params.push({
      paramName: "*"
    });
    regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
    : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
  } else if (end) {
    // When matching to the end, ignore trailing slashes
    regexpSource += "\\/*$";
  } else if (path !== "" && path !== "/") {
    // If our path is non-empty and contains anything beyond an initial slash,
    // then we have _some_ form of path in our regex, so we should expect to
    // match only if we find the end of this path segment.  Look for an optional
    // non-captured trailing slash (to match a portion of the URL) or the end
    // of the path (if we've matched to the end).  We used to do this with a
    // word boundary but that gives false positives on routes like
    // /user-preferences since `-` counts as a word boundary.
    regexpSource += "(?:(?=\\/|$))";
  } else ;
  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
  return [matcher, params];
}
function decodePath(value) {
  try {
    return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  } catch (error) {
    warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
    return value;
  }
}
/**
 * @private
 */
function stripBasename(pathname, basename) {
  if (basename === "/") return pathname;
  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
    return null;
  }
  // We want to leave trailing slash behavior in the user's control, so if they
  // specify a basename with a trailing slash, we should support it
  let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  let nextChar = pathname.charAt(startIndex);
  if (nextChar && nextChar !== "/") {
    // pathname does not start with basename/
    return null;
  }
  return pathname.slice(startIndex) || "/";
}
/**
 * Returns a resolved path object relative to the given pathname.
 *
 * @see https://reactrouter.com/utils/resolve-path
 */
function resolvePath(to, fromPathname) {
  if (fromPathname === void 0) {
    fromPathname = "/";
  }
  let {
    pathname: toPathname,
    search = "",
    hash = ""
  } = typeof to === "string" ? parsePath(to) : to;
  let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
  return {
    pathname,
    search: normalizeSearch(search),
    hash: normalizeHash(hash)
  };
}
function resolvePathname(relativePath, fromPathname) {
  let segments = fromPathname.replace(/\/+$/, "").split("/");
  let relativeSegments = relativePath.split("/");
  relativeSegments.forEach(segment => {
    if (segment === "..") {
      // Keep the root "" segment so the pathname starts at /
      if (segments.length > 1) segments.pop();
    } else if (segment !== ".") {
      segments.push(segment);
    }
  });
  return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field, dest, path) {
  return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "].  Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in <Link to=\"...\"> and the router will parse it for you.";
}
/**
 * @private
 *
 * When processing relative navigation we want to ignore ancestor routes that
 * do not contribute to the path, such that index/pathless layout routes don't
 * interfere.
 *
 * For example, when moving a route element into an index route and/or a
 * pathless layout route, relative link behavior contained within should stay
 * the same.  Both of the following examples should link back to the root:
 *
 *   <Route path="/">
 *     <Route path="accounts" element={<Link to=".."}>
 *   </Route>
 *
 *   <Route path="/">
 *     <Route path="accounts">
 *       <Route element={<AccountsLayout />}>       // <-- Does not contribute
 *         <Route index element={<Link to=".."} />  // <-- Does not contribute
 *       </Route
 *     </Route>
 *   </Route>
 */
function getPathContributingMatches(matches) {
  return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
}
// Return the array of pathnames for the current route matches - used to
// generate the routePathnames input for resolveTo()
function getResolveToMatches(matches, v7_relativeSplatPath) {
  let pathMatches = getPathContributingMatches(matches);
  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
  // match so we include splat values for "." links.  See:
  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
  if (v7_relativeSplatPath) {
    return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase);
  }
  return pathMatches.map(match => match.pathnameBase);
}
/**
 * @private
 */
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
  if (isPathRelative === void 0) {
    isPathRelative = false;
  }
  let to;
  if (typeof toArg === "string") {
    to = parsePath(toArg);
  } else {
    to = _extends({}, toArg);
    invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
    invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
    invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
  }
  let isEmptyPath = toArg === "" || to.pathname === "";
  let toPathname = isEmptyPath ? "/" : to.pathname;
  let from;
  // Routing is relative to the current pathname if explicitly requested.
  //
  // If a pathname is explicitly provided in `to`, it should be relative to the
  // route context. This is explained in `Note on `<Link to>` values` in our
  // migration guide from v5 as a means of disambiguation between `to` values
  // that begin with `/` and those that do not. However, this is problematic for
  // `to` values that do not provide a pathname. `to` can simply be a search or
  // hash string, in which case we should assume that the navigation is relative
  // to the current location's pathname and *not* the route pathname.
  if (toPathname == null) {
    from = locationPathname;
  } else {
    let routePathnameIndex = routePathnames.length - 1;
    // With relative="route" (the default), each leading .. segment means
    // "go up one route" instead of "go up one URL segment".  This is a key
    // difference from how <a href> works and a major reason we call this a
    // "to" value instead of a "href".
    if (!isPathRelative && toPathname.startsWith("..")) {
      let toSegments = toPathname.split("/");
      while (toSegments[0] === "..") {
        toSegments.shift();
        routePathnameIndex -= 1;
      }
      to.pathname = toSegments.join("/");
    }
    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  }
  let path = resolvePath(to, from);
  // Ensure the pathname has a trailing slash if the original "to" had one
  let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  // Or if this was a link to the current path which has a trailing slash
  let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
    path.pathname += "/";
  }
  return path;
}
/**
 * @private
 */
function getToPathname(to) {
  // Empty strings should be treated the same as / paths
  return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
}
/**
 * @private
 */
const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
/**
 * @private
 */
const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
/**
 * @private
 */
const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
/**
 * @private
 */
const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
/**
 * This is a shortcut for creating `application/json` responses. Converts `data`
 * to JSON and sets the `Content-Type` header.
 */
const json = function json(data, init) {
  if (init === void 0) {
    init = {};
  }
  let responseInit = typeof init === "number" ? {
    status: init
  } : init;
  let headers = new Headers(responseInit.headers);
  if (!headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json; charset=utf-8");
  }
  return new Response(JSON.stringify(data), _extends({}, responseInit, {
    headers
  }));
};
class AbortedDeferredError extends Error {}
class DeferredData {
  constructor(data, responseInit) {
    this.pendingKeysSet = new Set();
    this.subscribers = new Set();
    this.deferredKeys = [];
    invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
    // Set up an AbortController + Promise we can race against to exit early
    // cancellation
    let reject;
    this.abortPromise = new Promise((_, r) => reject = r);
    this.controller = new AbortController();
    let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
    this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
    this.controller.signal.addEventListener("abort", onAbort);
    this.data = Object.entries(data).reduce((acc, _ref2) => {
      let [key, value] = _ref2;
      return Object.assign(acc, {
        [key]: this.trackPromise(key, value)
      });
    }, {});
    if (this.done) {
      // All incoming values were resolved
      this.unlistenAbortSignal();
    }
    this.init = responseInit;
  }
  trackPromise(key, value) {
    if (!(value instanceof Promise)) {
      return value;
    }
    this.deferredKeys.push(key);
    this.pendingKeysSet.add(key);
    // We store a little wrapper promise that will be extended with
    // _data/_error props upon resolve/reject
    let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));
    // Register rejection listeners to avoid uncaught promise rejections on
    // errors or aborted deferred values
    promise.catch(() => {});
    Object.defineProperty(promise, "_tracked", {
      get: () => true
    });
    return promise;
  }
  onSettle(promise, key, error, data) {
    if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
      this.unlistenAbortSignal();
      Object.defineProperty(promise, "_error", {
        get: () => error
      });
      return Promise.reject(error);
    }
    this.pendingKeysSet.delete(key);
    if (this.done) {
      // Nothing left to abort!
      this.unlistenAbortSignal();
    }
    // If the promise was resolved/rejected with undefined, we'll throw an error as you
    // should always resolve with a value or null
    if (error === undefined && data === undefined) {
      let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`.");
      Object.defineProperty(promise, "_error", {
        get: () => undefinedError
      });
      this.emit(false, key);
      return Promise.reject(undefinedError);
    }
    if (data === undefined) {
      Object.defineProperty(promise, "_error", {
        get: () => error
      });
      this.emit(false, key);
      return Promise.reject(error);
    }
    Object.defineProperty(promise, "_data", {
      get: () => data
    });
    this.emit(false, key);
    return data;
  }
  emit(aborted, settledKey) {
    this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));
  }
  subscribe(fn) {
    this.subscribers.add(fn);
    return () => this.subscribers.delete(fn);
  }
  cancel() {
    this.controller.abort();
    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
    this.emit(true);
  }
  async resolveData(signal) {
    let aborted = false;
    if (!this.done) {
      let onAbort = () => this.cancel();
      signal.addEventListener("abort", onAbort);
      aborted = await new Promise(resolve => {
        this.subscribe(aborted => {
          signal.removeEventListener("abort", onAbort);
          if (aborted || this.done) {
            resolve(aborted);
          }
        });
      });
    }
    return aborted;
  }
  get done() {
    return this.pendingKeysSet.size === 0;
  }
  get unwrappedData() {
    invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
    return Object.entries(this.data).reduce((acc, _ref3) => {
      let [key, value] = _ref3;
      return Object.assign(acc, {
        [key]: unwrapTrackedPromise(value)
      });
    }, {});
  }
  get pendingKeys() {
    return Array.from(this.pendingKeysSet);
  }
}
function isTrackedPromise(value) {
  return value instanceof Promise && value._tracked === true;
}
function unwrapTrackedPromise(value) {
  if (!isTrackedPromise(value)) {
    return value;
  }
  if (value._error) {
    throw value._error;
  }
  return value._data;
}
const defer = function defer(data, init) {
  if (init === void 0) {
    init = {};
  }
  let responseInit = typeof init === "number" ? {
    status: init
  } : init;
  return new DeferredData(data, responseInit);
};
/**
 * A redirect response. Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const redirect = function redirect(url, init) {
  if (init === void 0) {
    init = 302;
  }
  let responseInit = init;
  if (typeof responseInit === "number") {
    responseInit = {
      status: responseInit
    };
  } else if (typeof responseInit.status === "undefined") {
    responseInit.status = 302;
  }
  let headers = new Headers(responseInit.headers);
  headers.set("Location", url);
  return new Response(null, _extends({}, responseInit, {
    headers
  }));
};
/**
 * A redirect response that will force a document reload to the new location.
 * Sets the status code and the `Location` header.
 * Defaults to "302 Found".
 */
const redirectDocument = (url, init) => {
  let response = redirect(url, init);
  response.headers.set("X-Remix-Reload-Document", "true");
  return response;
};
/**
 * @private
 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
 *
 * We don't export the class for public use since it's an implementation
 * detail, but we export the interface above so folks can build their own
 * abstractions around instances via isRouteErrorResponse()
 */
class ErrorResponseImpl {
  constructor(status, statusText, data, internal) {
    if (internal === void 0) {
      internal = false;
    }
    this.status = status;
    this.statusText = statusText || "";
    this.internal = internal;
    if (data instanceof Error) {
      this.data = data.toString();
      this.error = data;
    } else {
      this.data = data;
    }
  }
}
/**
 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
 * Response thrown from an action/loader
 */
function isRouteErrorResponse(error) {
  return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
}

const validMutationMethodsArr = ["post", "put", "patch", "delete"];
const validMutationMethods = new Set(validMutationMethodsArr);
const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
const validRequestMethods = new Set(validRequestMethodsArr);
const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
const redirectPreserveMethodStatusCodes = new Set([307, 308]);
const IDLE_NAVIGATION = {
  state: "idle",
  location: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined
};
const IDLE_FETCHER = {
  state: "idle",
  data: undefined,
  formMethod: undefined,
  formAction: undefined,
  formEncType: undefined,
  formData: undefined,
  json: undefined,
  text: undefined
};
const IDLE_BLOCKER = {
  state: "unblocked",
  proceed: undefined,
  reset: undefined,
  location: undefined
};
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const defaultMapRouteProperties = route => ({
  hasErrorBoundary: Boolean(route.hasErrorBoundary)
});
const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createRouter
////////////////////////////////////////////////////////////////////////////////
/**
 * Create a router and listen to history POP navigations
 */
function createRouter(init) {
  const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
  const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  const isServer = !isBrowser;
  invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
  let mapRouteProperties;
  if (init.mapRouteProperties) {
    mapRouteProperties = init.mapRouteProperties;
  } else if (init.detectErrorBoundary) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = init.detectErrorBoundary;
    mapRouteProperties = route => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }
  // Routes keyed by ID
  let manifest = {};
  // Routes in tree format for matching
  let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
  let inFlightDataRoutes;
  let basename = init.basename || "/";
  // Config driven behavior flags
  let future = _extends({
    v7_fetcherPersist: false,
    v7_normalizeFormMethod: false,
    v7_partialHydration: false,
    v7_prependBasename: false,
    v7_relativeSplatPath: false
  }, init.future);
  // Cleanup function for history
  let unlistenHistory = null;
  // Externally-provided functions to call on all state changes
  let subscribers = new Set();
  // Externally-provided object to hold scroll restoration locations during routing
  let savedScrollPositions = null;
  // Externally-provided function to get scroll restoration keys
  let getScrollRestorationKey = null;
  // Externally-provided function to get current scroll position
  let getScrollPosition = null;
  // One-time flag to control the initial hydration scroll restoration.  Because
  // we don't get the saved positions from <ScrollRestoration /> until _after_
  // the initial render, we need to manually trigger a separate updateState to
  // send along the restoreScrollPosition
  // Set to true if we have `hydrationData` since we assume we were SSR'd and that
  // SSR did the initial scroll restoration.
  let initialScrollRestored = init.hydrationData != null;
  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  let initialErrors = null;
  if (initialMatches == null) {
    // If we do not match a user-provided-route, fall back to the root
    // to allow the error boundary to take over
    let error = getInternalRouterError(404, {
      pathname: init.history.location.pathname
    });
    let {
      matches,
      route
    } = getShortCircuitMatches(dataRoutes);
    initialMatches = matches;
    initialErrors = {
      [route.id]: error
    };
  }
  let initialized;
  let hasLazyRoutes = initialMatches.some(m => m.route.lazy);
  let hasLoaders = initialMatches.some(m => m.route.loader);
  if (hasLazyRoutes) {
    // All initialMatches need to be loaded before we're ready.  If we have lazy
    // functions around still then we'll need to run them in initialize()
    initialized = false;
  } else if (!hasLoaders) {
    // If we've got no loaders to run, then we're good to go
    initialized = true;
  } else if (future.v7_partialHydration) {
    // If partial hydration is enabled, we're initialized so long as we were
    // provided with hydrationData for every route with a loader, and no loaders
    // were marked for explicit hydration
    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
    let errors = init.hydrationData ? init.hydrationData.errors : null;
    let isRouteInitialized = m => {
      // No loader, nothing to initialize
      if (!m.route.loader) return true;
      // Explicitly opting-in to running on hydration
      if (m.route.loader.hydrate === true) return false;
      // Otherwise, initialized if hydrated with data or an error
      return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined;
    };
    // If errors exist, don't consider routes below the boundary
    if (errors) {
      let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
      initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);
    } else {
      initialized = initialMatches.every(isRouteInitialized);
    }
  } else {
    // Without partial hydration - we're initialized if we were provided any
    // hydrationData - which is expected to be complete
    initialized = init.hydrationData != null;
  }
  let router;
  let state = {
    historyAction: init.history.action,
    location: init.history.location,
    matches: initialMatches,
    initialized,
    navigation: IDLE_NAVIGATION,
    // Don't restore on initial updateState() if we were SSR'd
    restoreScrollPosition: init.hydrationData != null ? false : null,
    preventScrollReset: false,
    revalidation: "idle",
    loaderData: init.hydrationData && init.hydrationData.loaderData || {},
    actionData: init.hydrationData && init.hydrationData.actionData || null,
    errors: init.hydrationData && init.hydrationData.errors || initialErrors,
    fetchers: new Map(),
    blockers: new Map()
  };
  // -- Stateful internal variables to manage navigations --
  // Current navigation in progress (to be committed in completeNavigation)
  let pendingAction = Action.Pop;
  // Should the current navigation prevent the scroll reset if scroll cannot
  // be restored?
  let pendingPreventScrollReset = false;
  // AbortController for the active navigation
  let pendingNavigationController;
  // Should the current navigation enable document.startViewTransition?
  let pendingViewTransitionEnabled = false;
  // Store applied view transitions so we can apply them on POP
  let appliedViewTransitions = new Map();
  // Cleanup function for persisting applied transitions to sessionStorage
  let removePageHideEventListener = null;
  // We use this to avoid touching history in completeNavigation if a
  // revalidation is entirely uninterrupted
  let isUninterruptedRevalidation = false;
  // Use this internal flag to force revalidation of all loaders:
  //  - submissions (completed or interrupted)
  //  - useRevalidator()
  //  - X-Remix-Revalidate (from redirect)
  let isRevalidationRequired = false;
  // Use this internal array to capture routes that require revalidation due
  // to a cancelled deferred on action submission
  let cancelledDeferredRoutes = [];
  // Use this internal array to capture fetcher loads that were cancelled by an
  // action navigation and require revalidation
  let cancelledFetcherLoads = [];
  // AbortControllers for any in-flight fetchers
  let fetchControllers = new Map();
  // Track loads based on the order in which they started
  let incrementingLoadId = 0;
  // Track the outstanding pending navigation data load to be compared against
  // the globally incrementing load when a fetcher load lands after a completed
  // navigation
  let pendingNavigationLoadId = -1;
  // Fetchers that triggered data reloads as a result of their actions
  let fetchReloadIds = new Map();
  // Fetchers that triggered redirect navigations
  let fetchRedirectIds = new Set();
  // Most recent href/match for fetcher.load calls for fetchers
  let fetchLoadMatches = new Map();
  // Ref-count mounted fetchers so we know when it's ok to clean them up
  let activeFetchers = new Map();
  // Fetchers that have requested a delete when using v7_fetcherPersist,
  // they'll be officially removed after they return to idle
  let deletedFetchers = new Set();
  // Store DeferredData instances for active route matches.  When a
  // route loader returns defer() we stick one in here.  Then, when a nested
  // promise resolves we update loaderData.  If a new navigation starts we
  // cancel active deferreds for eliminated routes.
  let activeDeferreds = new Map();
  // Store blocker functions in a separate Map outside of router state since
  // we don't need to update UI state if they change
  let blockerFunctions = new Map();
  // Flag to ignore the next history update, so we can revert the URL change on
  // a POP navigation that was blocked by the user without touching router state
  let ignoreNextHistoryUpdate = false;
  // Initialize the router, all side effects should be kicked off from here.
  // Implemented as a Fluent API for ease of:
  //   let router = createRouter(init).initialize();
  function initialize() {
    // If history informs us of a POP navigation, start the navigation but do not update
    // state.  We'll update our own state once the navigation completes
    unlistenHistory = init.history.listen(_ref => {
      let {
        action: historyAction,
        location,
        delta
      } = _ref;
      // Ignore this event if it was just us resetting the URL from a
      // blocked POP navigation
      if (ignoreNextHistoryUpdate) {
        ignoreNextHistoryUpdate = false;
        return;
      }
      warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs.  This can also happen if you are using " + "createHashRouter and the user manually changes the URL.");
      let blockerKey = shouldBlockNavigation({
        currentLocation: state.location,
        nextLocation: location,
        historyAction
      });
      if (blockerKey && delta != null) {
        // Restore the URL to match the current UI, but don't update router state
        ignoreNextHistoryUpdate = true;
        init.history.go(delta * -1);
        // Put the blocker into a blocked state
        updateBlocker(blockerKey, {
          state: "blocked",
          location,
          proceed() {
            updateBlocker(blockerKey, {
              state: "proceeding",
              proceed: undefined,
              reset: undefined,
              location
            });
            // Re-do the same POP navigation we just blocked
            init.history.go(delta);
          },
          reset() {
            let blockers = new Map(state.blockers);
            blockers.set(blockerKey, IDLE_BLOCKER);
            updateState({
              blockers
            });
          }
        });
        return;
      }
      return startNavigation(historyAction, location);
    });
    if (isBrowser) {
      // FIXME: This feels gross.  How can we cleanup the lines between
      // scrollRestoration/appliedTransitions persistance?
      restoreAppliedTransitions(routerWindow, appliedViewTransitions);
      let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
      routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
      removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
    }
    // Kick off initial data load if needed.  Use Pop to avoid modifying history
    // Note we don't do any handling of lazy here.  For SPA's it'll get handled
    // in the normal navigation flow.  For SSR it's expected that lazy modules are
    // resolved prior to router creation since we can't go into a fallbackElement
    // UI for SSR'd apps
    if (!state.initialized) {
      startNavigation(Action.Pop, state.location, {
        initialHydration: true
      });
    }
    return router;
  }
  // Clean up a router and it's side effects
  function dispose() {
    if (unlistenHistory) {
      unlistenHistory();
    }
    if (removePageHideEventListener) {
      removePageHideEventListener();
    }
    subscribers.clear();
    pendingNavigationController && pendingNavigationController.abort();
    state.fetchers.forEach((_, key) => deleteFetcher(key));
    state.blockers.forEach((_, key) => deleteBlocker(key));
  }
  // Subscribe to state updates for the router
  function subscribe(fn) {
    subscribers.add(fn);
    return () => subscribers.delete(fn);
  }
  // Update our state and notify the calling context of the change
  function updateState(newState, opts) {
    if (opts === void 0) {
      opts = {};
    }
    state = _extends({}, state, newState);
    // Prep fetcher cleanup so we can tell the UI which fetcher data entries
    // can be removed
    let completedFetchers = [];
    let deletedFetchersKeys = [];
    if (future.v7_fetcherPersist) {
      state.fetchers.forEach((fetcher, key) => {
        if (fetcher.state === "idle") {
          if (deletedFetchers.has(key)) {
            // Unmounted from the UI and can be totally removed
            deletedFetchersKeys.push(key);
          } else {
            // Returned to idle but still mounted in the UI, so semi-remains for
            // revalidations and such
            completedFetchers.push(key);
          }
        }
      });
    }
    // Iterate over a local copy so that if flushSync is used and we end up
    // removing and adding a new subscriber due to the useCallback dependencies,
    // we don't get ourselves into a loop calling the new subscriber immediately
    [...subscribers].forEach(subscriber => subscriber(state, {
      deletedFetchers: deletedFetchersKeys,
      unstable_viewTransitionOpts: opts.viewTransitionOpts,
      unstable_flushSync: opts.flushSync === true
    }));
    // Remove idle fetchers from state since we only care about in-flight fetchers.
    if (future.v7_fetcherPersist) {
      completedFetchers.forEach(key => state.fetchers.delete(key));
      deletedFetchersKeys.forEach(key => deleteFetcher(key));
    }
  }
  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
  // and setting state.[historyAction/location/matches] to the new route.
  // - Location is a required param
  // - Navigation will always be set to IDLE_NAVIGATION
  // - Can pass any other state in newState
  function completeNavigation(location, newState, _temp) {
    var _location$state, _location$state2;
    let {
      flushSync
    } = _temp === void 0 ? {} : _temp;
    // Deduce if we're in a loading/actionReload state:
    // - We have committed actionData in the store
    // - The current navigation was a mutation submission
    // - We're past the submitting state and into the loading state
    // - The location being loaded is not the result of a redirect
    let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
    let actionData;
    if (newState.actionData) {
      if (Object.keys(newState.actionData).length > 0) {
        actionData = newState.actionData;
      } else {
        // Empty actionData -> clear prior actionData due to an action error
        actionData = null;
      }
    } else if (isActionReload) {
      // Keep the current data if we're wrapping up the action reload
      actionData = state.actionData;
    } else {
      // Clear actionData on any other completed navigations
      actionData = null;
    }
    // Always preserve any existing loaderData from re-used routes
    let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
    // On a successful navigation we can assume we got through all blockers
    // so we can start fresh
    let blockers = state.blockers;
    if (blockers.size > 0) {
      blockers = new Map(blockers);
      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
    }
    // Always respect the user flag.  Otherwise don't reset on mutation
    // submission navigations unless they redirect
    let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
    if (inFlightDataRoutes) {
      dataRoutes = inFlightDataRoutes;
      inFlightDataRoutes = undefined;
    }
    if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {
      init.history.push(location, location.state);
    } else if (pendingAction === Action.Replace) {
      init.history.replace(location, location.state);
    }
    let viewTransitionOpts;
    // On POP, enable transitions if they were enabled on the original navigation
    if (pendingAction === Action.Pop) {
      // Forward takes precedence so they behave like the original navigation
      let priorPaths = appliedViewTransitions.get(state.location.pathname);
      if (priorPaths && priorPaths.has(location.pathname)) {
        viewTransitionOpts = {
          currentLocation: state.location,
          nextLocation: location
        };
      } else if (appliedViewTransitions.has(location.pathname)) {
        // If we don't have a previous forward nav, assume we're popping back to
        // the new location and enable if that location previously enabled
        viewTransitionOpts = {
          currentLocation: location,
          nextLocation: state.location
        };
      }
    } else if (pendingViewTransitionEnabled) {
      // Store the applied transition on PUSH/REPLACE
      let toPaths = appliedViewTransitions.get(state.location.pathname);
      if (toPaths) {
        toPaths.add(location.pathname);
      } else {
        toPaths = new Set([location.pathname]);
        appliedViewTransitions.set(state.location.pathname, toPaths);
      }
      viewTransitionOpts = {
        currentLocation: state.location,
        nextLocation: location
      };
    }
    updateState(_extends({}, newState, {
      actionData,
      loaderData,
      historyAction: pendingAction,
      location,
      initialized: true,
      navigation: IDLE_NAVIGATION,
      revalidation: "idle",
      restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
      preventScrollReset,
      blockers
    }), {
      viewTransitionOpts,
      flushSync: flushSync === true
    });
    // Reset stateful navigation vars
    pendingAction = Action.Pop;
    pendingPreventScrollReset = false;
    pendingViewTransitionEnabled = false;
    isUninterruptedRevalidation = false;
    isRevalidationRequired = false;
    cancelledDeferredRoutes = [];
    cancelledFetcherLoads = [];
  }
  // Trigger a navigation event, which can either be a numerical POP or a PUSH
  // replace with an optional submission
  async function navigate(to, opts) {
    if (typeof to === "number") {
      init.history.go(to);
      return;
    }
    let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);
    let {
      path,
      submission,
      error
    } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);
    let currentLocation = state.location;
    let nextLocation = createLocation(state.location, path, opts && opts.state);
    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
    // URL from window.location, so we need to encode it here so the behavior
    // remains the same as POP and non-data-router usages.  new URL() does all
    // the same encoding we'd get from a history.pushState/window.location read
    // without having to touch history
    nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
    let userReplace = opts && opts.replace != null ? opts.replace : undefined;
    let historyAction = Action.Push;
    if (userReplace === true) {
      historyAction = Action.Replace;
    } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
      // By default on submissions to the current location we REPLACE so that
      // users don't have to double-click the back button to get to the prior
      // location.  If the user redirects to a different location from the
      // action/loader this will be ignored and the redirect will be a PUSH
      historyAction = Action.Replace;
    }
    let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
    let flushSync = (opts && opts.unstable_flushSync) === true;
    let blockerKey = shouldBlockNavigation({
      currentLocation,
      nextLocation,
      historyAction
    });
    if (blockerKey) {
      // Put the blocker into a blocked state
      updateBlocker(blockerKey, {
        state: "blocked",
        location: nextLocation,
        proceed() {
          updateBlocker(blockerKey, {
            state: "proceeding",
            proceed: undefined,
            reset: undefined,
            location: nextLocation
          });
          // Send the same navigation through
          navigate(to, opts);
        },
        reset() {
          let blockers = new Map(state.blockers);
          blockers.set(blockerKey, IDLE_BLOCKER);
          updateState({
            blockers
          });
        }
      });
      return;
    }
    return await startNavigation(historyAction, nextLocation, {
      submission,
      // Send through the formData serialization error if we have one so we can
      // render at the right error boundary after we match routes
      pendingError: error,
      preventScrollReset,
      replace: opts && opts.replace,
      enableViewTransition: opts && opts.unstable_viewTransition,
      flushSync
    });
  }
  // Revalidate all current loaders.  If a navigation is in progress or if this
  // is interrupted by a navigation, allow this to "succeed" by calling all
  // loaders during the next loader round
  function revalidate() {
    interruptActiveLoads();
    updateState({
      revalidation: "loading"
    });
    // If we're currently submitting an action, we don't need to start a new
    // navigation, we'll just let the follow up loader execution call all loaders
    if (state.navigation.state === "submitting") {
      return;
    }
    // If we're currently in an idle state, start a new navigation for the current
    // action/location and mark it as uninterrupted, which will skip the history
    // update in completeNavigation
    if (state.navigation.state === "idle") {
      startNavigation(state.historyAction, state.location, {
        startUninterruptedRevalidation: true
      });
      return;
    }
    // Otherwise, if we're currently in a loading state, just start a new
    // navigation to the navigation.location but do not trigger an uninterrupted
    // revalidation so that history correctly updates once the navigation completes
    startNavigation(pendingAction || state.historyAction, state.navigation.location, {
      overrideNavigation: state.navigation
    });
  }
  // Start a navigation to the given action/location.  Can optionally provide a
  // overrideNavigation which will override the normalLoad in the case of a redirect
  // navigation
  async function startNavigation(historyAction, location, opts) {
    // Abort any in-progress navigations and start a new one. Unset any ongoing
    // uninterrupted revalidations unless told otherwise, since we want this
    // new navigation to update history normally
    pendingNavigationController && pendingNavigationController.abort();
    pendingNavigationController = null;
    pendingAction = historyAction;
    isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
    // Save the current scroll position every time we start a new navigation,
    // and track whether we should reset scroll on completion
    saveScrollPosition(state.location, state.matches);
    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let loadingNavigation = opts && opts.overrideNavigation;
    let matches = matchRoutes(routesToUse, location, basename);
    let flushSync = (opts && opts.flushSync) === true;
    // Short circuit with a 404 on the root error boundary if we match nothing
    if (!matches) {
      let error = getInternalRouterError(404, {
        pathname: location.pathname
      });
      let {
        matches: notFoundMatches,
        route
      } = getShortCircuitMatches(routesToUse);
      // Cancel all pending deferred on 404s since we don't keep any routes
      cancelActiveDeferreds();
      completeNavigation(location, {
        matches: notFoundMatches,
        loaderData: {},
        errors: {
          [route.id]: error
        }
      }, {
        flushSync
      });
      return;
    }
    // Short circuit if it's only a hash change and not a revalidation or
    // mutation submission.
    //
    // Ignore on initial page loads because since the initial load will always
    // be "same hash".  For example, on /page#hash and submit a <Form method="post">
    // which will default to a navigation to /page
    if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
      completeNavigation(location, {
        matches
      }, {
        flushSync
      });
      return;
    }
    // Create a controller/Request for this navigation
    pendingNavigationController = new AbortController();
    let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
    let pendingActionData;
    let pendingError;
    if (opts && opts.pendingError) {
      // If we have a pendingError, it means the user attempted a GET submission
      // with binary FormData so assign here and skip to handleLoaders.  That
      // way we handle calling loaders above the boundary etc.  It's not really
      // different from an actionError in that sense.
      pendingError = {
        [findNearestBoundary(matches).route.id]: opts.pendingError
      };
    } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
      // Call action if we received an action submission
      let actionOutput = await handleAction(request, location, opts.submission, matches, {
        replace: opts.replace,
        flushSync
      });
      if (actionOutput.shortCircuited) {
        return;
      }
      pendingActionData = actionOutput.pendingActionData;
      pendingError = actionOutput.pendingActionError;
      loadingNavigation = getLoadingNavigation(location, opts.submission);
      flushSync = false;
      // Create a GET request for the loaders
      request = new Request(request.url, {
        signal: request.signal
      });
    }
    // Call loaders
    let {
      shortCircuited,
      loaderData,
      errors
    } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionData, pendingError);
    if (shortCircuited) {
      return;
    }
    // Clean up now that the action/loaders have completed.  Don't clean up if
    // we short circuited because pendingNavigationController will have already
    // been assigned to a new controller for the next navigation
    pendingNavigationController = null;
    completeNavigation(location, _extends({
      matches
    }, pendingActionData ? {
      actionData: pendingActionData
    } : {}, {
      loaderData,
      errors
    }));
  }
  // Call the action matched by the leaf route for this navigation and handle
  // redirects/errors
  async function handleAction(request, location, submission, matches, opts) {
    if (opts === void 0) {
      opts = {};
    }
    interruptActiveLoads();
    // Put us in a submitting state
    let navigation = getSubmittingNavigation(location, submission);
    updateState({
      navigation
    }, {
      flushSync: opts.flushSync === true
    });
    // Call our action and get the result
    let result;
    let actionMatch = getTargetMatch(matches, location);
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      result = {
        type: ResultType.error,
        error: getInternalRouterError(405, {
          method: request.method,
          pathname: location.pathname,
          routeId: actionMatch.route.id
        })
      };
    } else {
      result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
      if (request.signal.aborted) {
        return {
          shortCircuited: true
        };
      }
    }
    if (isRedirectResult(result)) {
      let replace;
      if (opts && opts.replace != null) {
        replace = opts.replace;
      } else {
        // If the user didn't explicity indicate replace behavior, replace if
        // we redirected to the exact same location we're currently at to avoid
        // double back-buttons
        replace = result.location === state.location.pathname + state.location.search;
      }
      await startRedirectNavigation(state, result, {
        submission,
        replace
      });
      return {
        shortCircuited: true
      };
    }
    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
      // By default, all submissions are REPLACE navigations, but if the
      // action threw an error that'll be rendered in an errorElement, we fall
      // back to PUSH so that the user can use the back button to get back to
      // the pre-submission form location to try again
      if ((opts && opts.replace) !== true) {
        pendingAction = Action.Push;
      }
      return {
        // Send back an empty object we can use to clear out any prior actionData
        pendingActionData: {},
        pendingActionError: {
          [boundaryMatch.route.id]: result.error
        }
      };
    }
    if (isDeferredResult(result)) {
      throw getInternalRouterError(400, {
        type: "defer-action"
      });
    }
    return {
      pendingActionData: {
        [actionMatch.route.id]: result.data
      }
    };
  }
  // Call all applicable loaders for the given matches, handling redirects,
  // errors, etc.
  async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionData, pendingError) {
    // Figure out the right navigation we want to use for data loading
    let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
    // If this was a redirect from an action we don't have a "submission" but
    // we have it on the loading navigation so use that if available
    let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError);
    // Cancel pending deferreds for no-longer-matched routes or routes we're
    // about to reload.  Note that if this is an action reload we would have
    // already cancelled all pending deferreds so this would be a no-op
    cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
    pendingNavigationLoadId = ++incrementingLoadId;
    // Short circuit if we have no loaders to run
    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
      let updatedFetchers = markFetchRedirectsDone();
      completeNavigation(location, _extends({
        matches,
        loaderData: {},
        // Commit pending error if we're short circuiting
        errors: pendingError || null
      }, pendingActionData ? {
        actionData: pendingActionData
      } : {}, updatedFetchers ? {
        fetchers: new Map(state.fetchers)
      } : {}), {
        flushSync
      });
      return {
        shortCircuited: true
      };
    }
    // If this is an uninterrupted revalidation, we remain in our current idle
    // state.  If not, we need to switch to our loading state and load data,
    // preserving any new action data or existing action data (in the case of
    // a revalidation interrupting an actionReload)
    // If we have partialHydration enabled, then don't update the state for the
    // initial data load since it's not a "navigation"
    if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) {
      revalidatingFetchers.forEach(rf => {
        let fetcher = state.fetchers.get(rf.key);
        let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
        state.fetchers.set(rf.key, revalidatingFetcher);
      });
      let actionData = pendingActionData || state.actionData;
      updateState(_extends({
        navigation: loadingNavigation
      }, actionData ? Object.keys(actionData).length === 0 ? {
        actionData: null
      } : {
        actionData
      } : {}, revalidatingFetchers.length > 0 ? {
        fetchers: new Map(state.fetchers)
      } : {}), {
        flushSync
      });
    }
    revalidatingFetchers.forEach(rf => {
      if (fetchControllers.has(rf.key)) {
        abortFetcher(rf.key);
      }
      if (rf.controller) {
        // Fetchers use an independent AbortController so that aborting a fetcher
        // (via deleteFetcher) does not abort the triggering navigation that
        // triggered the revalidation
        fetchControllers.set(rf.key, rf.controller);
      }
    });
    // Proxy navigation abort through to revalidation fetchers
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
    if (pendingNavigationController) {
      pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
    }
    let {
      results,
      loaderResults,
      fetcherResults
    } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);
    if (request.signal.aborted) {
      return {
        shortCircuited: true
      };
    }
    // Clean up _after_ loaders have completed.  Don't clean up if we short
    // circuited because fetchControllers would have been aborted and
    // reassigned to new controllers for the next navigation
    if (pendingNavigationController) {
      pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
    }
    revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));
    // If any loaders returned a redirect Response, start a new REPLACE navigation
    let redirect = findRedirect(results);
    if (redirect) {
      if (redirect.idx >= matchesToLoad.length) {
        // If this redirect came from a fetcher make sure we mark it in
        // fetchRedirectIds so it doesn't get revalidated on the next set of
        // loader executions
        let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key;
        fetchRedirectIds.add(fetcherKey);
      }
      await startRedirectNavigation(state, redirect.result, {
        replace
      });
      return {
        shortCircuited: true
      };
    }
    // Process and commit output from loaders
    let {
      loaderData,
      errors
    } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds);
    // Wire up subscribers to update loaderData as promises settle
    activeDeferreds.forEach((deferredData, routeId) => {
      deferredData.subscribe(aborted => {
        // Note: No need to updateState here since the TrackedPromise on
        // loaderData is stable across resolve/reject
        // Remove this instance if we were aborted or if promises have settled
        if (aborted || deferredData.done) {
          activeDeferreds.delete(routeId);
        }
      });
    });
    // During partial hydration, preserve SSR errors for routes that don't re-run
    if (future.v7_partialHydration && initialHydration && state.errors) {
      Object.entries(state.errors).filter(_ref2 => {
        let [id] = _ref2;
        return !matchesToLoad.some(m => m.route.id === id);
      }).forEach(_ref3 => {
        let [routeId, error] = _ref3;
        errors = Object.assign(errors || {}, {
          [routeId]: error
        });
      });
    }
    let updatedFetchers = markFetchRedirectsDone();
    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
    let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
    return _extends({
      loaderData,
      errors
    }, shouldUpdateFetchers ? {
      fetchers: new Map(state.fetchers)
    } : {});
  }
  // Trigger a fetcher load/submit for the given fetcher key
  function fetch(key, routeId, href, opts) {
    if (isServer) {
      throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback.");
    }
    if (fetchControllers.has(key)) abortFetcher(key);
    let flushSync = (opts && opts.unstable_flushSync) === true;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);
    let matches = matchRoutes(routesToUse, normalizedPath, basename);
    if (!matches) {
      setFetcherError(key, routeId, getInternalRouterError(404, {
        pathname: normalizedPath
      }), {
        flushSync
      });
      return;
    }
    let {
      path,
      submission,
      error
    } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
    if (error) {
      setFetcherError(key, routeId, error, {
        flushSync
      });
      return;
    }
    let match = getTargetMatch(matches, path);
    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
    if (submission && isMutationMethod(submission.formMethod)) {
      handleFetcherAction(key, routeId, path, match, matches, flushSync, submission);
      return;
    }
    // Store off the match so we can call it's shouldRevalidate on subsequent
    // revalidations
    fetchLoadMatches.set(key, {
      routeId,
      path
    });
    handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission);
  }
  // Call the action for the matched fetcher.submit(), and then handle redirects,
  // errors, and revalidation
  async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) {
    interruptActiveLoads();
    fetchLoadMatches.delete(key);
    if (!match.route.action && !match.route.lazy) {
      let error = getInternalRouterError(405, {
        method: submission.formMethod,
        pathname: path,
        routeId: routeId
      });
      setFetcherError(key, routeId, error, {
        flushSync
      });
      return;
    }
    // Put this fetcher into it's submitting state
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
      flushSync
    });
    // Call the action for the fetcher
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
    fetchControllers.set(key, abortController);
    let originatingLoadId = incrementingLoadId;
    let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
    if (fetchRequest.signal.aborted) {
      // We can delete this so long as we weren't aborted by our own fetcher
      // re-submit which would have put _new_ controller is in fetchControllers
      if (fetchControllers.get(key) === abortController) {
        fetchControllers.delete(key);
      }
      return;
    }
    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
    // or redirects processed for unmounted fetchers so we just revert them to
    // idle
    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      }
      // Let SuccessResult's fall through for revalidation
    } else {
      if (isRedirectResult(actionResult)) {
        fetchControllers.delete(key);
        if (pendingNavigationLoadId > originatingLoadId) {
          // A new navigation was kicked off after our action started, so that
          // should take precedence over this redirect navigation.  We already
          // set isRevalidationRequired so all loaders for the new route should
          // fire unless opted out via shouldRevalidate
          updateFetcherState(key, getDoneFetcher(undefined));
          return;
        } else {
          fetchRedirectIds.add(key);
          updateFetcherState(key, getLoadingFetcher(submission));
          return startRedirectNavigation(state, actionResult, {
            fetcherSubmission: submission
          });
        }
      }
      // Process any non-redirect errors thrown
      if (isErrorResult(actionResult)) {
        setFetcherError(key, routeId, actionResult.error);
        return;
      }
    }
    if (isDeferredResult(actionResult)) {
      throw getInternalRouterError(400, {
        type: "defer-action"
      });
    }
    // Start the data load for current matches, or the next location if we're
    // in the middle of a navigation
    let nextLocation = state.navigation.location || state.location;
    let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
    invariant(matches, "Didn't find any matches after fetcher action");
    let loadId = ++incrementingLoadId;
    fetchReloadIds.set(key, loadId);
    let loadFetcher = getLoadingFetcher(submission, actionResult.data);
    state.fetchers.set(key, loadFetcher);
    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, {
      [match.route.id]: actionResult.data
    }, undefined // No need to send through errors since we short circuit above
    );
    // Put all revalidating fetchers into the loading state, except for the
    // current fetcher which we want to keep in it's current loading state which
    // contains it's action submission info + action data
    revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
      let staleKey = rf.key;
      let existingFetcher = state.fetchers.get(staleKey);
      let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
      state.fetchers.set(staleKey, revalidatingFetcher);
      if (fetchControllers.has(staleKey)) {
        abortFetcher(staleKey);
      }
      if (rf.controller) {
        fetchControllers.set(staleKey, rf.controller);
      }
    });
    updateState({
      fetchers: new Map(state.fetchers)
    });
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
    abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
    let {
      results,
      loaderResults,
      fetcherResults
    } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
    if (abortController.signal.aborted) {
      return;
    }
    abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
    fetchReloadIds.delete(key);
    fetchControllers.delete(key);
    revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
    let redirect = findRedirect(results);
    if (redirect) {
      if (redirect.idx >= matchesToLoad.length) {
        // If this redirect came from a fetcher make sure we mark it in
        // fetchRedirectIds so it doesn't get revalidated on the next set of
        // loader executions
        let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key;
        fetchRedirectIds.add(fetcherKey);
      }
      return startRedirectNavigation(state, redirect.result);
    }
    // Process and commit output from loaders
    let {
      loaderData,
      errors
    } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
    // Since we let revalidations complete even if the submitting fetcher was
    // deleted, only put it back to idle if it hasn't been deleted
    if (state.fetchers.has(key)) {
      let doneFetcher = getDoneFetcher(actionResult.data);
      state.fetchers.set(key, doneFetcher);
    }
    abortStaleFetchLoads(loadId);
    // If we are currently in a navigation loading state and this fetcher is
    // more recent than the navigation, we want the newer data so abort the
    // navigation and complete it with the fetcher data
    if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
      invariant(pendingAction, "Expected pending action");
      pendingNavigationController && pendingNavigationController.abort();
      completeNavigation(state.navigation.location, {
        matches,
        loaderData,
        errors,
        fetchers: new Map(state.fetchers)
      });
    } else {
      // otherwise just update with the fetcher data, preserving any existing
      // loaderData for loaders that did not need to reload.  We have to
      // manually merge here since we aren't going through completeNavigation
      updateState({
        errors,
        loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
        fetchers: new Map(state.fetchers)
      });
      isRevalidationRequired = false;
    }
  }
  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
  async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) {
    let existingFetcher = state.fetchers.get(key);
    updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
      flushSync
    });
    // Call the loader for this fetcher route match
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
    fetchControllers.set(key, abortController);
    let originatingLoadId = incrementingLoadId;
    let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
    // Deferred isn't supported for fetcher loads, await everything and treat it
    // as a normal load.  resolveDeferredData will return undefined if this
    // fetcher gets aborted, so we just leave result untouched and short circuit
    // below if that happens
    if (isDeferredResult(result)) {
      result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
    }
    // We can delete this so long as we weren't aborted by our our own fetcher
    // re-load which would have put _new_ controller is in fetchControllers
    if (fetchControllers.get(key) === abortController) {
      fetchControllers.delete(key);
    }
    if (fetchRequest.signal.aborted) {
      return;
    }
    // We don't want errors bubbling up or redirects followed for unmounted
    // fetchers, so short circuit here if it was removed from the UI
    if (deletedFetchers.has(key)) {
      updateFetcherState(key, getDoneFetcher(undefined));
      return;
    }
    // If the loader threw a redirect Response, start a new REPLACE navigation
    if (isRedirectResult(result)) {
      if (pendingNavigationLoadId > originatingLoadId) {
        // A new navigation was kicked off after our loader started, so that
        // should take precedence over this redirect navigation
        updateFetcherState(key, getDoneFetcher(undefined));
        return;
      } else {
        fetchRedirectIds.add(key);
        await startRedirectNavigation(state, result);
        return;
      }
    }
    // Process any non-redirect errors thrown
    if (isErrorResult(result)) {
      setFetcherError(key, routeId, result.error);
      return;
    }
    invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
    // Put the fetcher back into an idle state
    updateFetcherState(key, getDoneFetcher(result.data));
  }
  /**
   * Utility function to handle redirects returned from an action or loader.
   * Normally, a redirect "replaces" the navigation that triggered it.  So, for
   * example:
   *
   *  - user is on /a
   *  - user clicks a link to /b
   *  - loader for /b redirects to /c
   *
   * In a non-JS app the browser would track the in-flight navigation to /b and
   * then replace it with /c when it encountered the redirect response.  In
   * the end it would only ever update the URL bar with /c.
   *
   * In client-side routing using pushState/replaceState, we aim to emulate
   * this behavior and we also do not update history until the end of the
   * navigation (including processed redirects).  This means that we never
   * actually touch history until we've processed redirects, so we just use
   * the history action from the original navigation (PUSH or REPLACE).
   */
  async function startRedirectNavigation(state, redirect, _temp2) {
    let {
      submission,
      fetcherSubmission,
      replace
    } = _temp2 === void 0 ? {} : _temp2;
    if (redirect.revalidate) {
      isRevalidationRequired = true;
    }
    let redirectLocation = createLocation(state.location, redirect.location, {
      _isRedirect: true
    });
    invariant(redirectLocation, "Expected a location on the redirect navigation");
    if (isBrowser) {
      let isDocumentReload = false;
      if (redirect.reloadDocument) {
        // Hard reload if the response contained X-Remix-Reload-Document
        isDocumentReload = true;
      } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {
        const url = init.history.createURL(redirect.location);
        isDocumentReload =
        // Hard reload if it's an absolute URL to a new origin
        url.origin !== routerWindow.location.origin ||
        // Hard reload if it's an absolute URL that does not match our basename
        stripBasename(url.pathname, basename) == null;
      }
      if (isDocumentReload) {
        if (replace) {
          routerWindow.location.replace(redirect.location);
        } else {
          routerWindow.location.assign(redirect.location);
        }
        return;
      }
    }
    // There's no need to abort on redirects, since we don't detect the
    // redirect until the action/loaders have settled
    pendingNavigationController = null;
    let redirectHistoryAction = replace === true ? Action.Replace : Action.Push;
    // Use the incoming submission if provided, fallback on the active one in
    // state.navigation
    let {
      formMethod,
      formAction,
      formEncType
    } = state.navigation;
    if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
      submission = getSubmissionFromNavigation(state.navigation);
    }
    // If this was a 307/308 submission we want to preserve the HTTP method and
    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
    // redirected location
    let activeSubmission = submission || fetcherSubmission;
    if (redirectPreserveMethodStatusCodes.has(redirect.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
      await startNavigation(redirectHistoryAction, redirectLocation, {
        submission: _extends({}, activeSubmission, {
          formAction: redirect.location
        }),
        // Preserve this flag across redirects
        preventScrollReset: pendingPreventScrollReset
      });
    } else {
      // If we have a navigation submission, we will preserve it through the
      // redirect navigation
      let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
      await startNavigation(redirectHistoryAction, redirectLocation, {
        overrideNavigation,
        // Send fetcher submissions through for shouldRevalidate
        fetcherSubmission,
        // Preserve this flag across redirects
        preventScrollReset: pendingPreventScrollReset
      });
    }
  }
  async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {
    // Call all navigation loaders and revalidating fetcher loaders in parallel,
    // then slice off the results into separate arrays so we can handle them
    // accordingly
    let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath)), ...fetchersToLoad.map(f => {
      if (f.matches && f.match && f.controller) {
        return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, f.controller.signal), f.match, f.matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
      } else {
        let error = {
          type: ResultType.error,
          error: getInternalRouterError(404, {
            pathname: f.path
          })
        };
        return error;
      }
    })]);
    let loaderResults = results.slice(0, matchesToLoad.length);
    let fetcherResults = results.slice(matchesToLoad.length);
    await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), true)]);
    return {
      results,
      loaderResults,
      fetcherResults
    };
  }
  function interruptActiveLoads() {
    // Every interruption triggers a revalidation
    isRevalidationRequired = true;
    // Cancel pending route-level deferreds and mark cancelled routes for
    // revalidation
    cancelledDeferredRoutes.push(...cancelActiveDeferreds());
    // Abort in-flight fetcher loads
    fetchLoadMatches.forEach((_, key) => {
      if (fetchControllers.has(key)) {
        cancelledFetcherLoads.push(key);
        abortFetcher(key);
      }
    });
  }
  function updateFetcherState(key, fetcher, opts) {
    if (opts === void 0) {
      opts = {};
    }
    state.fetchers.set(key, fetcher);
    updateState({
      fetchers: new Map(state.fetchers)
    }, {
      flushSync: (opts && opts.flushSync) === true
    });
  }
  function setFetcherError(key, routeId, error, opts) {
    if (opts === void 0) {
      opts = {};
    }
    let boundaryMatch = findNearestBoundary(state.matches, routeId);
    deleteFetcher(key);
    updateState({
      errors: {
        [boundaryMatch.route.id]: error
      },
      fetchers: new Map(state.fetchers)
    }, {
      flushSync: (opts && opts.flushSync) === true
    });
  }
  function getFetcher(key) {
    if (future.v7_fetcherPersist) {
      activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
      // If this fetcher was previously marked for deletion, unmark it since we
      // have a new instance
      if (deletedFetchers.has(key)) {
        deletedFetchers.delete(key);
      }
    }
    return state.fetchers.get(key) || IDLE_FETCHER;
  }
  function deleteFetcher(key) {
    let fetcher = state.fetchers.get(key);
    // Don't abort the controller if this is a deletion of a fetcher.submit()
    // in it's loading phase since - we don't want to abort the corresponding
    // revalidation and want them to complete and land
    if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
      abortFetcher(key);
    }
    fetchLoadMatches.delete(key);
    fetchReloadIds.delete(key);
    fetchRedirectIds.delete(key);
    deletedFetchers.delete(key);
    state.fetchers.delete(key);
  }
  function deleteFetcherAndUpdateState(key) {
    if (future.v7_fetcherPersist) {
      let count = (activeFetchers.get(key) || 0) - 1;
      if (count <= 0) {
        activeFetchers.delete(key);
        deletedFetchers.add(key);
      } else {
        activeFetchers.set(key, count);
      }
    } else {
      deleteFetcher(key);
    }
    updateState({
      fetchers: new Map(state.fetchers)
    });
  }
  function abortFetcher(key) {
    let controller = fetchControllers.get(key);
    invariant(controller, "Expected fetch controller: " + key);
    controller.abort();
    fetchControllers.delete(key);
  }
  function markFetchersDone(keys) {
    for (let key of keys) {
      let fetcher = getFetcher(key);
      let doneFetcher = getDoneFetcher(fetcher.data);
      state.fetchers.set(key, doneFetcher);
    }
  }
  function markFetchRedirectsDone() {
    let doneKeys = [];
    let updatedFetchers = false;
    for (let key of fetchRedirectIds) {
      let fetcher = state.fetchers.get(key);
      invariant(fetcher, "Expected fetcher: " + key);
      if (fetcher.state === "loading") {
        fetchRedirectIds.delete(key);
        doneKeys.push(key);
        updatedFetchers = true;
      }
    }
    markFetchersDone(doneKeys);
    return updatedFetchers;
  }
  function abortStaleFetchLoads(landedId) {
    let yeetedKeys = [];
    for (let [key, id] of fetchReloadIds) {
      if (id < landedId) {
        let fetcher = state.fetchers.get(key);
        invariant(fetcher, "Expected fetcher: " + key);
        if (fetcher.state === "loading") {
          abortFetcher(key);
          fetchReloadIds.delete(key);
          yeetedKeys.push(key);
        }
      }
    }
    markFetchersDone(yeetedKeys);
    return yeetedKeys.length > 0;
  }
  function getBlocker(key, fn) {
    let blocker = state.blockers.get(key) || IDLE_BLOCKER;
    if (blockerFunctions.get(key) !== fn) {
      blockerFunctions.set(key, fn);
    }
    return blocker;
  }
  function deleteBlocker(key) {
    state.blockers.delete(key);
    blockerFunctions.delete(key);
  }
  // Utility function to update blockers, ensuring valid state transitions
  function updateBlocker(key, newBlocker) {
    let blocker = state.blockers.get(key) || IDLE_BLOCKER;
    // Poor mans state machine :)
    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
    invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
    let blockers = new Map(state.blockers);
    blockers.set(key, newBlocker);
    updateState({
      blockers
    });
  }
  function shouldBlockNavigation(_ref4) {
    let {
      currentLocation,
      nextLocation,
      historyAction
    } = _ref4;
    if (blockerFunctions.size === 0) {
      return;
    }
    // We ony support a single active blocker at the moment since we don't have
    // any compelling use cases for multi-blocker yet
    if (blockerFunctions.size > 1) {
      warning(false, "A router only supports one blocker at a time");
    }
    let entries = Array.from(blockerFunctions.entries());
    let [blockerKey, blockerFunction] = entries[entries.length - 1];
    let blocker = state.blockers.get(blockerKey);
    if (blocker && blocker.state === "proceeding") {
      // If the blocker is currently proceeding, we don't need to re-check
      // it and can let this navigation continue
      return;
    }
    // At this point, we know we're unblocked/blocked so we need to check the
    // user-provided blocker function
    if (blockerFunction({
      currentLocation,
      nextLocation,
      historyAction
    })) {
      return blockerKey;
    }
  }
  function cancelActiveDeferreds(predicate) {
    let cancelledRouteIds = [];
    activeDeferreds.forEach((dfd, routeId) => {
      if (!predicate || predicate(routeId)) {
        // Cancel the deferred - but do not remove from activeDeferreds here -
        // we rely on the subscribers to do that so our tests can assert proper
        // cleanup via _internalActiveDeferreds
        dfd.cancel();
        cancelledRouteIds.push(routeId);
        activeDeferreds.delete(routeId);
      }
    });
    return cancelledRouteIds;
  }
  // Opt in to capturing and reporting scroll positions during navigations,
  // used by the <ScrollRestoration> component
  function enableScrollRestoration(positions, getPosition, getKey) {
    savedScrollPositions = positions;
    getScrollPosition = getPosition;
    getScrollRestorationKey = getKey || null;
    // Perform initial hydration scroll restoration, since we miss the boat on
    // the initial updateState() because we've not yet rendered <ScrollRestoration/>
    // and therefore have no savedScrollPositions available
    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
      initialScrollRestored = true;
      let y = getSavedScrollPosition(state.location, state.matches);
      if (y != null) {
        updateState({
          restoreScrollPosition: y
        });
      }
    }
    return () => {
      savedScrollPositions = null;
      getScrollPosition = null;
      getScrollRestorationKey = null;
    };
  }
  function getScrollKey(location, matches) {
    if (getScrollRestorationKey) {
      let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));
      return key || location.key;
    }
    return location.key;
  }
  function saveScrollPosition(location, matches) {
    if (savedScrollPositions && getScrollPosition) {
      let key = getScrollKey(location, matches);
      savedScrollPositions[key] = getScrollPosition();
    }
  }
  function getSavedScrollPosition(location, matches) {
    if (savedScrollPositions) {
      let key = getScrollKey(location, matches);
      let y = savedScrollPositions[key];
      if (typeof y === "number") {
        return y;
      }
    }
    return null;
  }
  function _internalSetRoutes(newRoutes) {
    manifest = {};
    inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
  }
  router = {
    get basename() {
      return basename;
    },
    get future() {
      return future;
    },
    get state() {
      return state;
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return routerWindow;
    },
    initialize,
    subscribe,
    enableScrollRestoration,
    navigate,
    fetch,
    revalidate,
    // Passthrough to history-aware createHref used by useHref so we get proper
    // hash-aware URLs in DOM paths
    createHref: to => init.history.createHref(to),
    encodeLocation: to => init.history.encodeLocation(to),
    getFetcher,
    deleteFetcher: deleteFetcherAndUpdateState,
    dispose,
    getBlocker,
    deleteBlocker,
    _internalFetchControllers: fetchControllers,
    _internalActiveDeferreds: activeDeferreds,
    // TODO: Remove setRoutes, it's temporary to avoid dealing with
    // updating the tree while validating the update algorithm.
    _internalSetRoutes
  };
  return router;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createStaticHandler
////////////////////////////////////////////////////////////////////////////////
const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
function createStaticHandler(routes, opts) {
  invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  let manifest = {};
  let basename = (opts ? opts.basename : null) || "/";
  let mapRouteProperties;
  if (opts != null && opts.mapRouteProperties) {
    mapRouteProperties = opts.mapRouteProperties;
  } else if (opts != null && opts.detectErrorBoundary) {
    // If they are still using the deprecated version, wrap it with the new API
    let detectErrorBoundary = opts.detectErrorBoundary;
    mapRouteProperties = route => ({
      hasErrorBoundary: detectErrorBoundary(route)
    });
  } else {
    mapRouteProperties = defaultMapRouteProperties;
  }
  // Config driven behavior flags
  let future = _extends({
    v7_relativeSplatPath: false,
    v7_throwAbortReason: false
  }, opts ? opts.future : null);
  let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);
  /**
   * The query() method is intended for document requests, in which we want to
   * call an optional action and potentially multiple loaders for all nested
   * routes.  It returns a StaticHandlerContext object, which is very similar
   * to the router state (location, loaderData, actionData, errors, etc.) and
   * also adds SSR-specific information such as the statusCode and headers
   * from action/loaders Responses.
   *
   * It _should_ never throw and should report all errors through the
   * returned context.errors object, properly associating errors to their error
   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be
   * used to emulate React error boundaries during SSr by performing a second
   * pass only down to the boundaryId.
   *
   * The one exception where we do not return a StaticHandlerContext is when a
   * redirect response is returned or thrown from any action/loader.  We
   * propagate that out and return the raw Response so the HTTP server can
   * return it directly.
   */
  async function query(request, _temp3) {
    let {
      requestContext
    } = _temp3 === void 0 ? {} : _temp3;
    let url = new URL(request.url);
    let method = request.method;
    let location = createLocation("", createPath(url), null, "default");
    let matches = matchRoutes(dataRoutes, location, basename);
    // SSR supports HEAD requests while SPA doesn't
    if (!isValidMethod(method) && method !== "HEAD") {
      let error = getInternalRouterError(405, {
        method
      });
      let {
        matches: methodNotAllowedMatches,
        route
      } = getShortCircuitMatches(dataRoutes);
      return {
        basename,
        location,
        matches: methodNotAllowedMatches,
        loaderData: {},
        actionData: null,
        errors: {
          [route.id]: error
        },
        statusCode: error.status,
        loaderHeaders: {},
        actionHeaders: {},
        activeDeferreds: null
      };
    } else if (!matches) {
      let error = getInternalRouterError(404, {
        pathname: location.pathname
      });
      let {
        matches: notFoundMatches,
        route
      } = getShortCircuitMatches(dataRoutes);
      return {
        basename,
        location,
        matches: notFoundMatches,
        loaderData: {},
        actionData: null,
        errors: {
          [route.id]: error
        },
        statusCode: error.status,
        loaderHeaders: {},
        actionHeaders: {},
        activeDeferreds: null
      };
    }
    let result = await queryImpl(request, location, matches, requestContext);
    if (isResponse(result)) {
      return result;
    }
    // When returning StaticHandlerContext, we patch back in the location here
    // since we need it for React Context.  But this helps keep our submit and
    // loadRouteData operating on a Request instead of a Location
    return _extends({
      location,
      basename
    }, result);
  }
  /**
   * The queryRoute() method is intended for targeted route requests, either
   * for fetch ?_data requests or resource route requests.  In this case, we
   * are only ever calling a single action or loader, and we are returning the
   * returned value directly.  In most cases, this will be a Response returned
   * from the action/loader, but it may be a primitive or other value as well -
   * and in such cases the calling context should handle that accordingly.
   *
   * We do respect the throw/return differentiation, so if an action/loader
   * throws, then this method will throw the value.  This is important so we
   * can do proper boundary identification in Remix where a thrown Response
   * must go to the Catch Boundary but a returned Response is happy-path.
   *
   * One thing to note is that any Router-initiated Errors that make sense
   * to associate with a status code will be thrown as an ErrorResponse
   * instance which include the raw Error, such that the calling context can
   * serialize the error as they see fit while including the proper response
   * code.  Examples here are 404 and 405 errors that occur prior to reaching
   * any user-defined loaders.
   */
  async function queryRoute(request, _temp4) {
    let {
      routeId,
      requestContext
    } = _temp4 === void 0 ? {} : _temp4;
    let url = new URL(request.url);
    let method = request.method;
    let location = createLocation("", createPath(url), null, "default");
    let matches = matchRoutes(dataRoutes, location, basename);
    // SSR supports HEAD requests while SPA doesn't
    if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
      throw getInternalRouterError(405, {
        method
      });
    } else if (!matches) {
      throw getInternalRouterError(404, {
        pathname: location.pathname
      });
    }
    let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
    if (routeId && !match) {
      throw getInternalRouterError(403, {
        pathname: location.pathname,
        routeId
      });
    } else if (!match) {
      // This should never hit I don't think?
      throw getInternalRouterError(404, {
        pathname: location.pathname
      });
    }
    let result = await queryImpl(request, location, matches, requestContext, match);
    if (isResponse(result)) {
      return result;
    }
    let error = result.errors ? Object.values(result.errors)[0] : undefined;
    if (error !== undefined) {
      // If we got back result.errors, that means the loader/action threw
      // _something_ that wasn't a Response, but it's not guaranteed/required
      // to be an `instanceof Error` either, so we have to use throw here to
      // preserve the "error" state outside of queryImpl.
      throw error;
    }
    // Pick off the right state value to return
    if (result.actionData) {
      return Object.values(result.actionData)[0];
    }
    if (result.loaderData) {
      var _result$activeDeferre;
      let data = Object.values(result.loaderData)[0];
      if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
      }
      return data;
    }
    return undefined;
  }
  async function queryImpl(request, location, matches, requestContext, routeMatch) {
    invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
    try {
      if (isMutationMethod(request.method.toLowerCase())) {
        let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null);
        return result;
      }
      let result = await loadRouteData(request, matches, requestContext, routeMatch);
      return isResponse(result) ? result : _extends({}, result, {
        actionData: null,
        actionHeaders: {}
      });
    } catch (e) {
      // If the user threw/returned a Response in callLoaderOrAction, we throw
      // it to bail out and then return or throw here based on whether the user
      // returned or threw
      if (isQueryRouteResponse(e)) {
        if (e.type === ResultType.error) {
          throw e.response;
        }
        return e.response;
      }
      // Redirects are always returned since they don't propagate to catch
      // boundaries
      if (isRedirectResponse(e)) {
        return e;
      }
      throw e;
    }
  }
  async function submit(request, matches, actionMatch, requestContext, isRouteRequest) {
    let result;
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      let error = getInternalRouterError(405, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: actionMatch.route.id
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error
      };
    } else {
      result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, {
        isStaticRequest: true,
        isRouteRequest,
        requestContext
      });
      if (request.signal.aborted) {
        throwStaticHandlerAbortedError(request, isRouteRequest, future);
      }
    }
    if (isRedirectResult(result)) {
      // Uhhhh - this should never happen, we should always throw these from
      // callLoaderOrAction, but the type narrowing here keeps TS happy and we
      // can get back on the "throw all redirect responses" train here should
      // this ever happen :/
      throw new Response(null, {
        status: result.status,
        headers: {
          Location: result.location
        }
      });
    }
    if (isDeferredResult(result)) {
      let error = getInternalRouterError(400, {
        type: "defer-action"
      });
      if (isRouteRequest) {
        throw error;
      }
      result = {
        type: ResultType.error,
        error
      };
    }
    if (isRouteRequest) {
      // Note: This should only be non-Response values if we get here, since
      // isRouteRequest should throw any Response received in callLoaderOrAction
      if (isErrorResult(result)) {
        throw result.error;
      }
      return {
        matches: [actionMatch],
        loaderData: {},
        actionData: {
          [actionMatch.route.id]: result.data
        },
        errors: null,
        // Note: statusCode + headers are unused here since queryRoute will
        // return the raw Response or value
        statusCode: 200,
        loaderHeaders: {},
        actionHeaders: {},
        activeDeferreds: null
      };
    }
    if (isErrorResult(result)) {
      // Store off the pending error - we use it to determine which loaders
      // to call and will commit it when we complete the navigation
      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
      let context = await loadRouteData(request, matches, requestContext, undefined, {
        [boundaryMatch.route.id]: result.error
      });
      // action status codes take precedence over loader status codes
      return _extends({}, context, {
        statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,
        actionData: null,
        actionHeaders: _extends({}, result.headers ? {
          [actionMatch.route.id]: result.headers
        } : {})
      });
    }
    // Create a GET request for the loaders
    let loaderRequest = new Request(request.url, {
      headers: request.headers,
      redirect: request.redirect,
      signal: request.signal
    });
    let context = await loadRouteData(loaderRequest, matches, requestContext);
    return _extends({}, context, result.statusCode ? {
      statusCode: result.statusCode
    } : {}, {
      actionData: {
        [actionMatch.route.id]: result.data
      },
      actionHeaders: _extends({}, result.headers ? {
        [actionMatch.route.id]: result.headers
      } : {})
    });
  }
  async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) {
    let isRouteRequest = routeMatch != null;
    // Short circuit if we have no loaders to run (queryRoute())
    if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
      throw getInternalRouterError(400, {
        method: request.method,
        pathname: new URL(request.url).pathname,
        routeId: routeMatch == null ? void 0 : routeMatch.route.id
      });
    }
    let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);
    let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);
    // Short circuit if we have no loaders to run (query())
    if (matchesToLoad.length === 0) {
      return {
        matches,
        // Add a null for all matched routes for proper revalidation on the client
        loaderData: matches.reduce((acc, m) => Object.assign(acc, {
          [m.route.id]: null
        }), {}),
        errors: pendingActionError || null,
        statusCode: 200,
        loaderHeaders: {},
        activeDeferreds: null
      };
    }
    let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, {
      isStaticRequest: true,
      isRouteRequest,
      requestContext
    }))]);
    if (request.signal.aborted) {
      throwStaticHandlerAbortedError(request, isRouteRequest, future);
    }
    // Process and commit output from loaders
    let activeDeferreds = new Map();
    let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds);
    // Add a null for any non-loader matches for proper revalidation on the client
    let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));
    matches.forEach(match => {
      if (!executedLoaders.has(match.route.id)) {
        context.loaderData[match.route.id] = null;
      }
    });
    return _extends({}, context, {
      matches,
      activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
    });
  }
  return {
    dataRoutes,
    query,
    queryRoute
  };
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Helpers
////////////////////////////////////////////////////////////////////////////////
/**
 * Given an existing StaticHandlerContext and an error thrown at render time,
 * provide an updated StaticHandlerContext suitable for a second SSR render
 */
function getStaticContextFromError(routes, context, error) {
  let newContext = _extends({}, context, {
    statusCode: isRouteErrorResponse(error) ? error.status : 500,
    errors: {
      [context._deepestRenderedBoundaryId || routes[0].id]: error
    }
  });
  return newContext;
}
function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
    throw request.signal.reason;
  }
  let method = isRouteRequest ? "queryRoute" : "query";
  throw new Error(method + "() call aborted: " + request.method + " " + request.url);
}
function isSubmissionNavigation(opts) {
  return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined);
}
function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  let contextualMatches;
  let activeRouteMatch;
  if (fromRouteId) {
    // Grab matches up to the calling route so our route-relative logic is
    // relative to the correct source route
    contextualMatches = [];
    for (let match of matches) {
      contextualMatches.push(match);
      if (match.route.id === fromRouteId) {
        activeRouteMatch = match;
        break;
      }
    }
  } else {
    contextualMatches = matches;
    activeRouteMatch = matches[matches.length - 1];
  }
  // Resolve the relative path
  let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
  // When `to` is not specified we inherit search/hash from the current
  // location, unlike when to="." and we just inherit the path.
  // See https://github.com/remix-run/remix/issues/927
  if (to == null) {
    path.search = location.search;
    path.hash = location.hash;
  }
  // Add an ?index param for matched index routes if we don't already have one
  if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) {
    path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  }
  // If we're operating within a basename, prepend it to the pathname.  If
  // this is a root navigation, then just use the raw basename which allows
  // the basename to have full control over the presence of a trailing slash
  // on root actions
  if (prependBasename && basename !== "/") {
    path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  }
  return createPath(path);
}
// Normalize navigation options by converting formMethod=GET formData objects to
// URLSearchParams so they behave identically to links with query params
function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
  // Return location verbatim on non-submission navigations
  if (!opts || !isSubmissionNavigation(opts)) {
    return {
      path
    };
  }
  if (opts.formMethod && !isValidMethod(opts.formMethod)) {
    return {
      path,
      error: getInternalRouterError(405, {
        method: opts.formMethod
      })
    };
  }
  let getInvalidBodyError = () => ({
    path,
    error: getInternalRouterError(400, {
      type: "invalid-body"
    })
  });
  // Create a Submission on non-GET navigations
  let rawFormMethod = opts.formMethod || "get";
  let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
  let formAction = stripHashFromPath(path);
  if (opts.body !== undefined) {
    if (opts.formEncType === "text/plain") {
      // text only support POST/PUT/PATCH/DELETE submissions
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }
      let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?
      // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
      Array.from(opts.body.entries()).reduce((acc, _ref5) => {
        let [name, value] = _ref5;
        return "" + acc + name + "=" + value + "\n";
      }, "") : String(opts.body);
      return {
        path,
        submission: {
          formMethod,
          formAction,
          formEncType: opts.formEncType,
          formData: undefined,
          json: undefined,
          text
        }
      };
    } else if (opts.formEncType === "application/json") {
      // json only supports POST/PUT/PATCH/DELETE submissions
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }
      try {
        let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
        return {
          path,
          submission: {
            formMethod,
            formAction,
            formEncType: opts.formEncType,
            formData: undefined,
            json,
            text: undefined
          }
        };
      } catch (e) {
        return getInvalidBodyError();
      }
    }
  }
  invariant(typeof FormData === "function", "FormData is not available in this environment");
  let searchParams;
  let formData;
  if (opts.formData) {
    searchParams = convertFormDataToSearchParams(opts.formData);
    formData = opts.formData;
  } else if (opts.body instanceof FormData) {
    searchParams = convertFormDataToSearchParams(opts.body);
    formData = opts.body;
  } else if (opts.body instanceof URLSearchParams) {
    searchParams = opts.body;
    formData = convertSearchParamsToFormData(searchParams);
  } else if (opts.body == null) {
    searchParams = new URLSearchParams();
    formData = new FormData();
  } else {
    try {
      searchParams = new URLSearchParams(opts.body);
      formData = convertSearchParamsToFormData(searchParams);
    } catch (e) {
      return getInvalidBodyError();
    }
  }
  let submission = {
    formMethod,
    formAction,
    formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
    formData,
    json: undefined,
    text: undefined
  };
  if (isMutationMethod(submission.formMethod)) {
    return {
      path,
      submission
    };
  }
  // Flatten submission onto URLSearchParams for GET submissions
  let parsedPath = parsePath(path);
  // On GET navigation submissions we can drop the ?index param from the
  // resulting location since all loaders will run.  But fetcher GET submissions
  // only run a single loader so we need to preserve any incoming ?index params
  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
    searchParams.append("index", "");
  }
  parsedPath.search = "?" + searchParams;
  return {
    path: createPath(parsedPath),
    submission
  };
}
// Filter out all routes below any caught error as they aren't going to
// render so we don't need to load them
function getLoaderMatchesUntilBoundary(matches, boundaryId) {
  let boundaryMatches = matches;
  if (boundaryId) {
    let index = matches.findIndex(m => m.route.id === boundaryId);
    if (index >= 0) {
      boundaryMatches = matches.slice(0, index);
    }
  }
  return boundaryMatches;
}
function getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) {
  let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined;
  let currentUrl = history.createURL(state.location);
  let nextUrl = history.createURL(location);
  // Pick navigation matches that are net-new or qualify for revalidation
  let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;
  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
  let navigationMatches = boundaryMatches.filter((match, index) => {
    let {
      route
    } = match;
    if (route.lazy) {
      // We haven't loaded this route yet so we don't know if it's got a loader!
      return true;
    }
    if (route.loader == null) {
      return false;
    }
    if (isInitialLoad) {
      if (route.loader.hydrate) {
        return true;
      }
      return state.loaderData[route.id] === undefined && (
      // Don't re-run if the loader ran and threw an error
      !state.errors || state.errors[route.id] === undefined);
    }
    // Always call the loader on new route instances and pending defer cancellations
    if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
      return true;
    }
    // This is the default implementation for when we revalidate.  If the route
    // provides it's own implementation, then we give them full control but
    // provide this value so they can leverage it if needed after they check
    // their own specific use cases
    let currentRouteMatch = state.matches[index];
    let nextRouteMatch = match;
    return shouldRevalidateLoader(match, _extends({
      currentUrl,
      currentParams: currentRouteMatch.params,
      nextUrl,
      nextParams: nextRouteMatch.params
    }, submission, {
      actionResult,
      defaultShouldRevalidate:
      // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
      isRevalidationRequired ||
      // Clicked the same link, resubmitted a GET form
      currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
      // Search params affect all loaders
      currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
    }));
  });
  // Pick fetcher.loads that need to be revalidated
  let revalidatingFetchers = [];
  fetchLoadMatches.forEach((f, key) => {
    // Don't revalidate:
    //  - on initial load (shouldn't be any fetchers then anyway)
    //  - if fetcher won't be present in the subsequent render
    //    - no longer matches the URL (v7_fetcherPersist=false)
    //    - was unmounted but persisted due to v7_fetcherPersist=true
    if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
      return;
    }
    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
    // If the fetcher path no longer matches, push it in with null matches so
    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is
    // currently only a use-case for Remix HMR where the route tree can change
    // at runtime and remove a route previously loaded via a fetcher
    if (!fetcherMatches) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: null,
        match: null,
        controller: null
      });
      return;
    }
    // Revalidating fetchers are decoupled from the route matches since they
    // load from a static href.  They revalidate based on explicit revalidation
    // (submission, useRevalidator, or X-Remix-Revalidate)
    let fetcher = state.fetchers.get(key);
    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
    let shouldRevalidate = false;
    if (fetchRedirectIds.has(key)) {
      // Never trigger a revalidation of an actively redirecting fetcher
      shouldRevalidate = false;
    } else if (cancelledFetcherLoads.includes(key)) {
      // Always revalidate if the fetcher was cancelled
      shouldRevalidate = true;
    } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
      // If the fetcher hasn't ever completed loading yet, then this isn't a
      // revalidation, it would just be a brand new load if an explicit
      // revalidation is required
      shouldRevalidate = isRevalidationRequired;
    } else {
      // Otherwise fall back on any user-defined shouldRevalidate, defaulting
      // to explicit revalidations only
      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
        currentUrl,
        currentParams: state.matches[state.matches.length - 1].params,
        nextUrl,
        nextParams: matches[matches.length - 1].params
      }, submission, {
        actionResult,
        defaultShouldRevalidate: isRevalidationRequired
      }));
    }
    if (shouldRevalidate) {
      revalidatingFetchers.push({
        key,
        routeId: f.routeId,
        path: f.path,
        matches: fetcherMatches,
        match: fetcherMatch,
        controller: new AbortController()
      });
    }
  });
  return [navigationMatches, revalidatingFetchers];
}
function isNewLoader(currentLoaderData, currentMatch, match) {
  let isNew =
  // [a] -> [a, b]
  !currentMatch ||
  // [a, b] -> [a, c]
  match.route.id !== currentMatch.route.id;
  // Handle the case that we don't have data for a re-used route, potentially
  // from a prior error or from a cancelled pending deferred
  let isMissingData = currentLoaderData[match.route.id] === undefined;
  // Always load if this is a net-new route or we don't yet have data
  return isNew || isMissingData;
}
function isNewRouteInstance(currentMatch, match) {
  let currentPath = currentMatch.route.path;
  return (
    // param change for this match, /users/123 -> /users/456
    currentMatch.pathname !== match.pathname ||
    // splat param changed, which is not present in match.path
    // e.g. /files/images/avatar.jpg -> files/finances.xls
    currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  );
}
function shouldRevalidateLoader(loaderMatch, arg) {
  if (loaderMatch.route.shouldRevalidate) {
    let routeChoice = loaderMatch.route.shouldRevalidate(arg);
    if (typeof routeChoice === "boolean") {
      return routeChoice;
    }
  }
  return arg.defaultShouldRevalidate;
}
/**
 * Execute route.lazy() methods to lazily load route modules (loader, action,
 * shouldRevalidate) and update the routeManifest in place which shares objects
 * with dataRoutes so those get updated as well.
 */
async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
  if (!route.lazy) {
    return;
  }
  let lazyRoute = await route.lazy();
  // If the lazy route function was executed and removed by another parallel
  // call then we can return - first lazy() to finish wins because the return
  // value of lazy is expected to be static
  if (!route.lazy) {
    return;
  }
  let routeToUpdate = manifest[route.id];
  invariant(routeToUpdate, "No route found in manifest");
  // Update the route in place.  This should be safe because there's no way
  // we could yet be sitting on this route as we can't get there without
  // resolving lazy() first.
  //
  // This is different than the HMR "update" use-case where we may actively be
  // on the route being updated.  The main concern boils down to "does this
  // mutation affect any ongoing navigations or any current state.matches
  // values?".  If not, it should be safe to update in place.
  let routeUpdates = {};
  for (let lazyRouteProperty in lazyRoute) {
    let staticRouteValue = routeToUpdate[lazyRouteProperty];
    let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
    // This property isn't static since it should always be updated based
    // on the route updates
    lazyRouteProperty !== "hasErrorBoundary";
    warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored."));
    if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
      routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
    }
  }
  // Mutate the route with the provided updates.  Do this first so we pass
  // the updated version to mapRouteProperties
  Object.assign(routeToUpdate, routeUpdates);
  // Mutate the `hasErrorBoundary` property on the route based on the route
  // updates and remove the `lazy` function so we don't resolve the lazy
  // route again.
  Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
    lazy: undefined
  }));
}
async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, v7_relativeSplatPath, opts) {
  if (opts === void 0) {
    opts = {};
  }
  let resultType;
  let result;
  let onReject;
  let runHandler = handler => {
    // Setup a promise we can race against so that abort signals short circuit
    let reject;
    let abortPromise = new Promise((_, r) => reject = r);
    onReject = () => reject();
    request.signal.addEventListener("abort", onReject);
    return Promise.race([handler({
      request,
      params: match.params,
      context: opts.requestContext
    }), abortPromise]);
  };
  try {
    let handler = match.route[type];
    if (match.route.lazy) {
      if (handler) {
        // Run statically defined handler in parallel with lazy()
        let handlerError;
        let values = await Promise.all([
        // If the handler throws, don't let it immediately bubble out,
        // since we need to let the lazy() execution finish so we know if this
        // route has a boundary that can handle the error
        runHandler(handler).catch(e => {
          handlerError = e;
        }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]);
        if (handlerError) {
          throw handlerError;
        }
        result = values[0];
      } else {
        // Load lazy route module, then run any returned handler
        await loadLazyRouteModule(match.route, mapRouteProperties, manifest);
        handler = match.route[type];
        if (handler) {
          // Handler still run even if we got interrupted to maintain consistency
          // with un-abortable behavior of handler execution on non-lazy or
          // previously-lazy-loaded routes
          result = await runHandler(handler);
        } else if (type === "action") {
          let url = new URL(request.url);
          let pathname = url.pathname + url.search;
          throw getInternalRouterError(405, {
            method: request.method,
            pathname,
            routeId: match.route.id
          });
        } else {
          // lazy() route has no loader to run.  Short circuit here so we don't
          // hit the invariant below that errors on returning undefined.
          return {
            type: ResultType.data,
            data: undefined
          };
        }
      }
    } else if (!handler) {
      let url = new URL(request.url);
      let pathname = url.pathname + url.search;
      throw getInternalRouterError(404, {
        pathname
      });
    } else {
      result = await runHandler(handler);
    }
    invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
  } catch (e) {
    resultType = ResultType.error;
    result = e;
  } finally {
    if (onReject) {
      request.signal.removeEventListener("abort", onReject);
    }
  }
  if (isResponse(result)) {
    let status = result.status;
    // Process redirects
    if (redirectStatusCodes.has(status)) {
      let location = result.headers.get("Location");
      invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
      // Support relative routing in internal redirects
      if (!ABSOLUTE_URL_REGEX.test(location)) {
        location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location, v7_relativeSplatPath);
      } else if (!opts.isStaticRequest) {
        // Strip off the protocol+origin for same-origin + same-basename absolute
        // redirects. If this is a static request, we can let it go back to the
        // browser as-is
        let currentUrl = new URL(request.url);
        let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location);
        let isSameBasename = stripBasename(url.pathname, basename) != null;
        if (url.origin === currentUrl.origin && isSameBasename) {
          location = url.pathname + url.search + url.hash;
        }
      }
      // Don't process redirects in the router during static requests requests.
      // Instead, throw the Response and let the server handle it with an HTTP
      // redirect.  We also update the Location header in place in this flow so
      // basename and relative routing is taken into account
      if (opts.isStaticRequest) {
        result.headers.set("Location", location);
        throw result;
      }
      return {
        type: ResultType.redirect,
        status,
        location,
        revalidate: result.headers.get("X-Remix-Revalidate") !== null,
        reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null
      };
    }
    // For SSR single-route requests, we want to hand Responses back directly
    // without unwrapping.  We do this with the QueryRouteResponse wrapper
    // interface so we can know whether it was returned or thrown
    if (opts.isRouteRequest) {
      let queryRouteResponse = {
        type: resultType === ResultType.error ? ResultType.error : ResultType.data,
        response: result
      };
      throw queryRouteResponse;
    }
    let data;
    try {
      let contentType = result.headers.get("Content-Type");
      // Check between word boundaries instead of startsWith() due to the last
      // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
      if (contentType && /\bapplication\/json\b/.test(contentType)) {
        if (result.body == null) {
          data = null;
        } else {
          data = await result.json();
        }
      } else {
        data = await result.text();
      }
    } catch (e) {
      return {
        type: ResultType.error,
        error: e
      };
    }
    if (resultType === ResultType.error) {
      return {
        type: resultType,
        error: new ErrorResponseImpl(status, result.statusText, data),
        headers: result.headers
      };
    }
    return {
      type: ResultType.data,
      data,
      statusCode: result.status,
      headers: result.headers
    };
  }
  if (resultType === ResultType.error) {
    return {
      type: resultType,
      error: result
    };
  }
  if (isDeferredData(result)) {
    var _result$init, _result$init2;
    return {
      type: ResultType.deferred,
      deferredData: result,
      statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
      headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers)
    };
  }
  return {
    type: ResultType.data,
    data: result
  };
}
// Utility method for creating the Request instances for loaders/actions during
// client-side navigations and fetches.  During SSR we will always have a
// Request instance from the static handler (query/queryRoute)
function createClientSideRequest(history, location, signal, submission) {
  let url = history.createURL(stripHashFromPath(location)).toString();
  let init = {
    signal
  };
  if (submission && isMutationMethod(submission.formMethod)) {
    let {
      formMethod,
      formEncType
    } = submission;
    // Didn't think we needed this but it turns out unlike other methods, patch
    // won't be properly normalized to uppercase and results in a 405 error.
    // See: https://fetch.spec.whatwg.org/#concept-method
    init.method = formMethod.toUpperCase();
    if (formEncType === "application/json") {
      init.headers = new Headers({
        "Content-Type": formEncType
      });
      init.body = JSON.stringify(submission.json);
    } else if (formEncType === "text/plain") {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.text;
    } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = convertFormDataToSearchParams(submission.formData);
    } else {
      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
      init.body = submission.formData;
    }
  }
  return new Request(url, init);
}
function convertFormDataToSearchParams(formData) {
  let searchParams = new URLSearchParams();
  for (let [key, value] of formData.entries()) {
    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
    searchParams.append(key, typeof value === "string" ? value : value.name);
  }
  return searchParams;
}
function convertSearchParamsToFormData(searchParams) {
  let formData = new FormData();
  for (let [key, value] of searchParams.entries()) {
    formData.append(key, value);
  }
  return formData;
}
function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {
  // Fill in loaderData/errors from our loaders
  let loaderData = {};
  let errors = null;
  let statusCode;
  let foundError = false;
  let loaderHeaders = {};
  // Process loader results into state.loaderData/state.errors
  results.forEach((result, index) => {
    let id = matchesToLoad[index].route.id;
    invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
    if (isErrorResult(result)) {
      // Look upwards from the matched route for the closest ancestor
      // error boundary, defaulting to the root match
      let boundaryMatch = findNearestBoundary(matches, id);
      let error = result.error;
      // If we have a pending action error, we report it at the highest-route
      // that throws a loader error, and then clear it out to indicate that
      // it was consumed
      if (pendingError) {
        error = Object.values(pendingError)[0];
        pendingError = undefined;
      }
      errors = errors || {};
      // Prefer higher error values if lower errors bubble to the same boundary
      if (errors[boundaryMatch.route.id] == null) {
        errors[boundaryMatch.route.id] = error;
      }
      // Clear our any prior loaderData for the throwing route
      loaderData[id] = undefined;
      // Once we find our first (highest) error, we set the status code and
      // prevent deeper status codes from overriding
      if (!foundError) {
        foundError = true;
        statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
      }
      if (result.headers) {
        loaderHeaders[id] = result.headers;
      }
    } else {
      if (isDeferredResult(result)) {
        activeDeferreds.set(id, result.deferredData);
        loaderData[id] = result.deferredData.data;
      } else {
        loaderData[id] = result.data;
      }
      // Error status codes always override success status codes, but if all
      // loaders are successful we take the deepest status code.
      if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
        statusCode = result.statusCode;
      }
      if (result.headers) {
        loaderHeaders[id] = result.headers;
      }
    }
  });
  // If we didn't consume the pending action error (i.e., all loaders
  // resolved), then consume it here.  Also clear out any loaderData for the
  // throwing route
  if (pendingError) {
    errors = pendingError;
    loaderData[Object.keys(pendingError)[0]] = undefined;
  }
  return {
    loaderData,
    errors,
    statusCode: statusCode || 200,
    loaderHeaders
  };
}
function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {
  let {
    loaderData,
    errors
  } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds);
  // Process results from our revalidating fetchers
  for (let index = 0; index < revalidatingFetchers.length; index++) {
    let {
      key,
      match,
      controller
    } = revalidatingFetchers[index];
    invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result");
    let result = fetcherResults[index];
    // Process fetcher non-redirect errors
    if (controller && controller.signal.aborted) {
      // Nothing to do for aborted fetchers
      continue;
    } else if (isErrorResult(result)) {
      let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
      if (!(errors && errors[boundaryMatch.route.id])) {
        errors = _extends({}, errors, {
          [boundaryMatch.route.id]: result.error
        });
      }
      state.fetchers.delete(key);
    } else if (isRedirectResult(result)) {
      // Should never get here, redirects should get processed above, but we
      // keep this to type narrow to a success result in the else
      invariant(false, "Unhandled fetcher revalidation redirect");
    } else if (isDeferredResult(result)) {
      // Should never get here, deferred data should be awaited for fetchers
      // in resolveDeferredResults
      invariant(false, "Unhandled fetcher deferred data");
    } else {
      let doneFetcher = getDoneFetcher(result.data);
      state.fetchers.set(key, doneFetcher);
    }
  }
  return {
    loaderData,
    errors
  };
}
function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  let mergedLoaderData = _extends({}, newLoaderData);
  for (let match of matches) {
    let id = match.route.id;
    if (newLoaderData.hasOwnProperty(id)) {
      if (newLoaderData[id] !== undefined) {
        mergedLoaderData[id] = newLoaderData[id];
      }
    } else if (loaderData[id] !== undefined && match.route.loader) {
      // Preserve existing keys not included in newLoaderData and where a loader
      // wasn't removed by HMR
      mergedLoaderData[id] = loaderData[id];
    }
    if (errors && errors.hasOwnProperty(id)) {
      // Don't keep any loader data below the boundary
      break;
    }
  }
  return mergedLoaderData;
}
// Find the nearest error boundary, looking upwards from the leaf route (or the
// route specified by routeId) for the closest ancestor error boundary,
// defaulting to the root match
function findNearestBoundary(matches, routeId) {
  let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
  return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
}
function getShortCircuitMatches(routes) {
  // Prefer a root layout route if present, otherwise shim in a route object
  let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
    id: "__shim-error-route__"
  };
  return {
    matches: [{
      params: {},
      pathname: "",
      pathnameBase: "",
      route
    }],
    route
  };
}
function getInternalRouterError(status, _temp5) {
  let {
    pathname,
    routeId,
    method,
    type
  } = _temp5 === void 0 ? {} : _temp5;
  let statusText = "Unknown Server Error";
  let errorMessage = "Unknown @remix-run/router error";
  if (status === 400) {
    statusText = "Bad Request";
    if (method && pathname && routeId) {
      errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request.";
    } else if (type === "defer-action") {
      errorMessage = "defer() is not supported in actions";
    } else if (type === "invalid-body") {
      errorMessage = "Unable to encode submission body";
    }
  } else if (status === 403) {
    statusText = "Forbidden";
    errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\"";
  } else if (status === 404) {
    statusText = "Not Found";
    errorMessage = "No route matches URL \"" + pathname + "\"";
  } else if (status === 405) {
    statusText = "Method Not Allowed";
    if (method && pathname && routeId) {
      errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request.";
    } else if (method) {
      errorMessage = "Invalid request method \"" + method.toUpperCase() + "\"";
    }
  }
  return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
}
// Find any returned redirect errors, starting from the lowest match
function findRedirect(results) {
  for (let i = results.length - 1; i >= 0; i--) {
    let result = results[i];
    if (isRedirectResult(result)) {
      return {
        result,
        idx: i
      };
    }
  }
}
function stripHashFromPath(path) {
  let parsedPath = typeof path === "string" ? parsePath(path) : path;
  return createPath(_extends({}, parsedPath, {
    hash: ""
  }));
}
function isHashChangeOnly(a, b) {
  if (a.pathname !== b.pathname || a.search !== b.search) {
    return false;
  }
  if (a.hash === "") {
    // /page -> /page#hash
    return b.hash !== "";
  } else if (a.hash === b.hash) {
    // /page#hash -> /page#hash
    return true;
  } else if (b.hash !== "") {
    // /page#hash -> /page#other
    return true;
  }
  // If the hash is removed the browser will re-perform a request to the server
  // /page#hash -> /page
  return false;
}
function isDeferredResult(result) {
  return result.type === ResultType.deferred;
}
function isErrorResult(result) {
  return result.type === ResultType.error;
}
function isRedirectResult(result) {
  return (result && result.type) === ResultType.redirect;
}
function isDeferredData(value) {
  let deferred = value;
  return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
}
function isResponse(value) {
  return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
}
function isRedirectResponse(result) {
  if (!isResponse(result)) {
    return false;
  }
  let status = result.status;
  let location = result.headers.get("Location");
  return status >= 300 && status <= 399 && location != null;
}
function isQueryRouteResponse(obj) {
  return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error);
}
function isValidMethod(method) {
  return validRequestMethods.has(method.toLowerCase());
}
function isMutationMethod(method) {
  return validMutationMethods.has(method.toLowerCase());
}
async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) {
  for (let index = 0; index < results.length; index++) {
    let result = results[index];
    let match = matchesToLoad[index];
    // If we don't have a match, then we can have a deferred result to do
    // anything with.  This is for revalidating fetchers where the route was
    // removed during HMR
    if (!match) {
      continue;
    }
    let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
    let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
    if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
      // Note: we do not have to touch activeDeferreds here since we race them
      // against the signal in resolveDeferredData and they'll get aborted
      // there if needed
      let signal = signals[index];
      invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result");
      await resolveDeferredData(result, signal, isFetcher).then(result => {
        if (result) {
          results[index] = result || results[index];
        }
      });
    }
  }
}
async function resolveDeferredData(result, signal, unwrap) {
  if (unwrap === void 0) {
    unwrap = false;
  }
  let aborted = await result.deferredData.resolveData(signal);
  if (aborted) {
    return;
  }
  if (unwrap) {
    try {
      return {
        type: ResultType.data,
        data: result.deferredData.unwrappedData
      };
    } catch (e) {
      // Handle any TrackedPromise._error values encountered while unwrapping
      return {
        type: ResultType.error,
        error: e
      };
    }
  }
  return {
    type: ResultType.data,
    data: result.deferredData.data
  };
}
function hasNakedIndexQuery(search) {
  return new URLSearchParams(search).getAll("index").some(v => v === "");
}
function getTargetMatch(matches, location) {
  let search = typeof location === "string" ? parsePath(location).search : location.search;
  if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
    // Return the leaf index route when index is present
    return matches[matches.length - 1];
  }
  // Otherwise grab the deepest "path contributing" match (ignoring index and
  // pathless layout routes)
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches[pathMatches.length - 1];
}
function getSubmissionFromNavigation(navigation) {
  let {
    formMethod,
    formAction,
    formEncType,
    text,
    formData,
    json
  } = navigation;
  if (!formMethod || !formAction || !formEncType) {
    return;
  }
  if (text != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json: undefined,
      text
    };
  } else if (formData != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData,
      json: undefined,
      text: undefined
    };
  } else if (json !== undefined) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: undefined,
      json,
      text: undefined
    };
  }
}
function getLoadingNavigation(location, submission) {
  if (submission) {
    let navigation = {
      state: "loading",
      location,
      formMethod: submission.formMethod,
      formAction: submission.formAction,
      formEncType: submission.formEncType,
      formData: submission.formData,
      json: submission.json,
      text: submission.text
    };
    return navigation;
  } else {
    let navigation = {
      state: "loading",
      location,
      formMethod: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined
    };
    return navigation;
  }
}
function getSubmittingNavigation(location, submission) {
  let navigation = {
    state: "submitting",
    location,
    formMethod: submission.formMethod,
    formAction: submission.formAction,
    formEncType: submission.formEncType,
    formData: submission.formData,
    json: submission.json,
    text: submission.text
  };
  return navigation;
}
function getLoadingFetcher(submission, data) {
  if (submission) {
    let fetcher = {
      state: "loading",
      formMethod: submission.formMethod,
      formAction: submission.formAction,
      formEncType: submission.formEncType,
      formData: submission.formData,
      json: submission.json,
      text: submission.text,
      data
    };
    return fetcher;
  } else {
    let fetcher = {
      state: "loading",
      formMethod: undefined,
      formAction: undefined,
      formEncType: undefined,
      formData: undefined,
      json: undefined,
      text: undefined,
      data
    };
    return fetcher;
  }
}
function getSubmittingFetcher(submission, existingFetcher) {
  let fetcher = {
    state: "submitting",
    formMethod: submission.formMethod,
    formAction: submission.formAction,
    formEncType: submission.formEncType,
    formData: submission.formData,
    json: submission.json,
    text: submission.text,
    data: existingFetcher ? existingFetcher.data : undefined
  };
  return fetcher;
}
function getDoneFetcher(data) {
  let fetcher = {
    state: "idle",
    formMethod: undefined,
    formAction: undefined,
    formEncType: undefined,
    formData: undefined,
    json: undefined,
    text: undefined,
    data
  };
  return fetcher;
}
function restoreAppliedTransitions(_window, transitions) {
  try {
    let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
    if (sessionPositions) {
      let json = JSON.parse(sessionPositions);
      for (let [k, v] of Object.entries(json || {})) {
        if (v && Array.isArray(v)) {
          transitions.set(k, new Set(v || []));
        }
      }
    }
  } catch (e) {
    // no-op, use default empty object
  }
}
function persistAppliedTransitions(_window, transitions) {
  if (transitions.size > 0) {
    let json = {};
    for (let [k, v] of transitions) {
      json[k] = [...v];
    }
    try {
      _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
    } catch (error) {
      warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
    }
  }
}
//#endregion


//# sourceMappingURL=router.js.map


/***/ }),

/***/ 5615:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

/*! jsonpath 1.1.1 */

(function(f){if(true){module.exports=f()}else // removed by dead control flow
{ var g; }})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=undefined;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=undefined;for(var o=0;o<r.length;o++)s(r[o]);return s})({"./aesprim":[function(require,module,exports){
/*
  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 (typeof define === 'function' && define.amd) {
        define(['exports'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.esprima = {}));
    }
}(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 == 0x40) ||  (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 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)) {
                    return scanOctalLiteral(start);
                }

                // decimal number starts with '0' such as '09' is illegal.
                if (ch && isDecimalDigit(ch.charCodeAt(0))) {
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
                }
            }

            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') {
            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;

        // 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) {
            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 previousAllowIn, expr, args, property, startToken;

        startToken = lookahead;

        previousAllowIn = state.allowIn;
        state.allowIn = true;
        expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
        state.allowIn = previousAllowIn;

        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);
        }

        return expr;
    }

    function parseLeftHandSideExpression() {
        var previousAllowIn, expr, property, startToken;

        startToken = lookahead;

        previousAllowIn = state.allowIn;
        expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
        state.allowIn = previousAllowIn;

        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;

        init = test = update = null;

        expectKeyword('for');

        expect('(');

        if (match(';')) {
            lex();
        } else {
            if (matchKeyword('var') || matchKeyword('let')) {
                state.allowIn = false;
                init = parseForVariableDeclaration();
                state.allowIn = true;

                if (init.declarations.length === 1 && matchKeyword('in')) {
                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                }
            } else {
                state.allowIn = false;
                init = parseExpression();
                state.allowIn = true;

                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.2';

    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 : */

},{}],1:[function(require,module,exports){
(function (process){
/* parser generated by jison 0.4.13 */
/*
  Returns a Parser object of the following structure:

  Parser: {
    yy: {}
  }

  Parser.prototype: {
    yy: {},
    trace: function(),
    symbols_: {associative list: name ==> number},
    terminals_: {associative list: number ==> name},
    productions_: [...],
    performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),
    table: [...],
    defaultActions: {...},
    parseError: function(str, hash),
    parse: function(input),

    lexer: {
        EOF: 1,
        parseError: function(str, hash),
        setInput: function(input),
        input: function(),
        unput: function(str),
        more: function(),
        less: function(n),
        pastInput: function(),
        upcomingInput: function(),
        showPosition: function(),
        test_match: function(regex_match_array, rule_index),
        next: function(),
        lex: function(),
        begin: function(condition),
        popState: function(),
        _currentRules: function(),
        topState: function(),
        pushState: function(condition),

        options: {
            ranges: boolean           (optional: true ==> token location info will include a .range[] member)
            flex: boolean             (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)
            backtrack_lexer: boolean  (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)
        },

        performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
        rules: [...],
        conditions: {associative list: name ==> set},
    }
  }


  token location info (@$, _$, etc.): {
    first_line: n,
    last_line: n,
    first_column: n,
    last_column: n,
    range: [start_number, end_number]       (where the numbers are indexes into the input string, regular zero-based)
  }


  the parseError function receives a 'hash' object with these members for lexer and parser errors: {
    text:        (matched text)
    token:       (the produced terminal token, if any)
    line:        (yylineno)
  }
  while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {
    loc:         (yylloc)
    expected:    (string describing the set of expected tokens)
    recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)
  }
*/
var parser = (function(){
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"JSON_PATH":3,"DOLLAR":4,"PATH_COMPONENTS":5,"LEADING_CHILD_MEMBER_EXPRESSION":6,"PATH_COMPONENT":7,"MEMBER_COMPONENT":8,"SUBSCRIPT_COMPONENT":9,"CHILD_MEMBER_COMPONENT":10,"DESCENDANT_MEMBER_COMPONENT":11,"DOT":12,"MEMBER_EXPRESSION":13,"DOT_DOT":14,"STAR":15,"IDENTIFIER":16,"SCRIPT_EXPRESSION":17,"INTEGER":18,"END":19,"CHILD_SUBSCRIPT_COMPONENT":20,"DESCENDANT_SUBSCRIPT_COMPONENT":21,"[":22,"SUBSCRIPT":23,"]":24,"SUBSCRIPT_EXPRESSION":25,"SUBSCRIPT_EXPRESSION_LIST":26,"SUBSCRIPT_EXPRESSION_LISTABLE":27,",":28,"STRING_LITERAL":29,"ARRAY_SLICE":30,"FILTER_EXPRESSION":31,"QQ_STRING":32,"Q_STRING":33,"$accept":0,"$end":1},
terminals_: {2:"error",4:"DOLLAR",12:"DOT",14:"DOT_DOT",15:"STAR",16:"IDENTIFIER",17:"SCRIPT_EXPRESSION",18:"INTEGER",19:"END",22:"[",24:"]",28:",",30:"ARRAY_SLICE",31:"FILTER_EXPRESSION",32:"QQ_STRING",33:"Q_STRING"},
productions_: [0,[3,1],[3,2],[3,1],[3,2],[5,1],[5,2],[7,1],[7,1],[8,1],[8,1],[10,2],[6,1],[11,2],[13,1],[13,1],[13,1],[13,1],[13,1],[9,1],[9,1],[20,3],[21,4],[23,1],[23,1],[26,1],[26,3],[27,1],[27,1],[27,1],[25,1],[25,1],[25,1],[29,1],[29,1]],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */
/**/) {
/* this == yyval */
if (!yy.ast) {
    yy.ast = _ast;
    _ast.initialize();
}

var $0 = $$.length - 1;
switch (yystate) {
case 1:yy.ast.set({ expression: { type: "root", value: $$[$0] } }); yy.ast.unshift(); return yy.ast.yield()
// removed by dead control flow
{}
case 2:yy.ast.set({ expression: { type: "root", value: $$[$0-1] } }); yy.ast.unshift(); return yy.ast.yield()
// removed by dead control flow
{}
case 3:yy.ast.unshift(); return yy.ast.yield()
// removed by dead control flow
{}
case 4:yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $$[$0-1] }}); yy.ast.unshift(); return yy.ast.yield()
// removed by dead control flow
{}
case 5:
break;
case 6:
break;
case 7:yy.ast.set({ operation: "member" }); yy.ast.push()
break;
case 8:yy.ast.set({ operation: "subscript" }); yy.ast.push() 
break;
case 9:yy.ast.set({ scope: "child" })
break;
case 10:yy.ast.set({ scope: "descendant" })
break;
case 11:
break;
case 12:yy.ast.set({ scope: "child", operation: "member" })
break;
case 13:
break;
case 14:yy.ast.set({ expression: { type: "wildcard", value: $$[$0] } })
break;
case 15:yy.ast.set({ expression: { type: "identifier", value: $$[$0] } })
break;
case 16:yy.ast.set({ expression: { type: "script_expression", value: $$[$0] } })
break;
case 17:yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($$[$0]) } })
break;
case 18:
break;
case 19:yy.ast.set({ scope: "child" })
break;
case 20:yy.ast.set({ scope: "descendant" })
break;
case 21:
break;
case 22:
break;
case 23:
break;
case 24:$$[$0].length > 1? yy.ast.set({ expression: { type: "union", value: $$[$0] } }) : this.$ = $$[$0]
break;
case 25:this.$ = [$$[$0]]
break;
case 26:this.$ = $$[$0-2].concat($$[$0])
break;
case 27:this.$ = { expression: { type: "numeric_literal", value: parseInt($$[$0]) } }; yy.ast.set(this.$)
break;
case 28:this.$ = { expression: { type: "string_literal", value: $$[$0] } }; yy.ast.set(this.$)
break;
case 29:this.$ = { expression: { type: "slice", value: $$[$0] } }; yy.ast.set(this.$)
break;
case 30:this.$ = { expression: { type: "wildcard", value: $$[$0] } }; yy.ast.set(this.$)
break;
case 31:this.$ = { expression: { type: "script_expression", value: $$[$0] } }; yy.ast.set(this.$)
break;
case 32:this.$ = { expression: { type: "filter_expression", value: $$[$0] } }; yy.ast.set(this.$)
break;
case 33:this.$ = $$[$0]
break;
case 34:this.$ = $$[$0]
break;
}
},
table: [{3:1,4:[1,2],6:3,13:4,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{1:[3]},{1:[2,1],5:10,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,3],5:21,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,12],12:[2,12],14:[2,12],22:[2,12]},{1:[2,14],12:[2,14],14:[2,14],22:[2,14]},{1:[2,15],12:[2,15],14:[2,15],22:[2,15]},{1:[2,16],12:[2,16],14:[2,16],22:[2,16]},{1:[2,17],12:[2,17],14:[2,17],22:[2,17]},{1:[2,18],12:[2,18],14:[2,18],22:[2,18]},{1:[2,2],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,5],12:[2,5],14:[2,5],22:[2,5]},{1:[2,7],12:[2,7],14:[2,7],22:[2,7]},{1:[2,8],12:[2,8],14:[2,8],22:[2,8]},{1:[2,9],12:[2,9],14:[2,9],22:[2,9]},{1:[2,10],12:[2,10],14:[2,10],22:[2,10]},{1:[2,19],12:[2,19],14:[2,19],22:[2,19]},{1:[2,20],12:[2,20],14:[2,20],22:[2,20]},{13:23,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{13:24,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9],22:[1,25]},{15:[1,29],17:[1,30],18:[1,33],23:26,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{1:[2,4],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,6],12:[2,6],14:[2,6],22:[2,6]},{1:[2,11],12:[2,11],14:[2,11],22:[2,11]},{1:[2,13],12:[2,13],14:[2,13],22:[2,13]},{15:[1,29],17:[1,30],18:[1,33],23:38,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{24:[1,39]},{24:[2,23]},{24:[2,24],28:[1,40]},{24:[2,30]},{24:[2,31]},{24:[2,32]},{24:[2,25],28:[2,25]},{24:[2,27],28:[2,27]},{24:[2,28],28:[2,28]},{24:[2,29],28:[2,29]},{24:[2,33],28:[2,33]},{24:[2,34],28:[2,34]},{24:[1,41]},{1:[2,21],12:[2,21],14:[2,21],22:[2,21]},{18:[1,33],27:42,29:34,30:[1,35],32:[1,36],33:[1,37]},{1:[2,22],12:[2,22],14:[2,22],22:[2,22]},{24:[2,26],28:[2,26]}],
defaultActions: {27:[2,23],29:[2,30],30:[2,31],31:[2,32]},
parseError: function parseError(str, hash) {
    if (hash.recoverable) {
        this.trace(str);
    } else {
        throw new Error(str);
    }
},
parse: function parse(input) {
    var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
    var args = lstack.slice.call(arguments, 1);
    this.lexer.setInput(input);
    this.lexer.yy = this.yy;
    this.yy.lexer = this.lexer;
    this.yy.parser = this;
    if (typeof this.lexer.yylloc == 'undefined') {
        this.lexer.yylloc = {};
    }
    var yyloc = this.lexer.yylloc;
    lstack.push(yyloc);
    var ranges = this.lexer.options && this.lexer.options.ranges;
    if (typeof this.yy.parseError === 'function') {
        this.parseError = this.yy.parseError;
    } else {
        this.parseError = Object.getPrototypeOf(this).parseError;
    }
    function popStack(n) {
        stack.length = stack.length - 2 * n;
        vstack.length = vstack.length - n;
        lstack.length = lstack.length - n;
    }
    function lex() {
        var token;
        token = self.lexer.lex() || EOF;
        if (typeof token !== 'number') {
            token = self.symbols_[token] || token;
        }
        return token;
    }
    var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
    while (true) {
        state = stack[stack.length - 1];
        if (this.defaultActions[state]) {
            action = this.defaultActions[state];
        } else {
            if (symbol === null || typeof symbol == 'undefined') {
                symbol = lex();
            }
            action = table[state] && table[state][symbol];
        }
                    if (typeof action === 'undefined' || !action.length || !action[0]) {
                var errStr = '';
                expected = [];
                for (p in table[state]) {
                    if (this.terminals_[p] && p > TERROR) {
                        expected.push('\'' + this.terminals_[p] + '\'');
                    }
                }
                if (this.lexer.showPosition) {
                    errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + this.lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\'';
                } else {
                    errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\'');
                }
                this.parseError(errStr, {
                    text: this.lexer.match,
                    token: this.terminals_[symbol] || symbol,
                    line: this.lexer.yylineno,
                    loc: yyloc,
                    expected: expected
                });
            }
        if (action[0] instanceof Array && action.length > 1) {
            throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);
        }
        switch (action[0]) {
        case 1:
            stack.push(symbol);
            vstack.push(this.lexer.yytext);
            lstack.push(this.lexer.yylloc);
            stack.push(action[1]);
            symbol = null;
            if (!preErrorSymbol) {
                yyleng = this.lexer.yyleng;
                yytext = this.lexer.yytext;
                yylineno = this.lexer.yylineno;
                yyloc = this.lexer.yylloc;
                if (recovering > 0) {
                    recovering--;
                }
            } else {
                symbol = preErrorSymbol;
                preErrorSymbol = null;
            }
            break;
        case 2:
            len = this.productions_[action[1]][1];
            yyval.$ = vstack[vstack.length - len];
            yyval._$ = {
                first_line: lstack[lstack.length - (len || 1)].first_line,
                last_line: lstack[lstack.length - 1].last_line,
                first_column: lstack[lstack.length - (len || 1)].first_column,
                last_column: lstack[lstack.length - 1].last_column
            };
            if (ranges) {
                yyval._$.range = [
                    lstack[lstack.length - (len || 1)].range[0],
                    lstack[lstack.length - 1].range[1]
                ];
            }
            r = this.performAction.apply(yyval, [
                yytext,
                yyleng,
                yylineno,
                this.yy,
                action[1],
                vstack,
                lstack
            ].concat(args));
            if (typeof r !== 'undefined') {
                return r;
            }
            if (len) {
                stack = stack.slice(0, -1 * len * 2);
                vstack = vstack.slice(0, -1 * len);
                lstack = lstack.slice(0, -1 * len);
            }
            stack.push(this.productions_[action[1]][0]);
            vstack.push(yyval.$);
            lstack.push(yyval._$);
            newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
            stack.push(newState);
            break;
        case 3:
            return true;
        }
    }
    return true;
}};
var _ast = {

  initialize: function() {
    this._nodes = [];
    this._node = {};
    this._stash = [];
  },

  set: function(props) {
    for (var k in props) this._node[k] = props[k];
    return this._node;
  },

  node: function(obj) {
    if (arguments.length) this._node = obj;
    return this._node;
  },

  push: function() {
    this._nodes.push(this._node);
    this._node = {};
  },

  unshift: function() {
    this._nodes.unshift(this._node);
    this._node = {};
  },

  yield: function() {
    var _nodes = this._nodes;
    this.initialize();
    return _nodes;
  }
};
/* generated by jison-lex 0.2.1 */
var lexer = (function(){
var lexer = {

EOF:1,

parseError:function parseError(str, hash) {
        if (this.yy.parser) {
            this.yy.parser.parseError(str, hash);
        } else {
            throw new Error(str);
        }
    },

// resets the lexer, sets new input
setInput:function (input) {
        this._input = input;
        this._more = this._backtrack = this.done = false;
        this.yylineno = this.yyleng = 0;
        this.yytext = this.matched = this.match = '';
        this.conditionStack = ['INITIAL'];
        this.yylloc = {
            first_line: 1,
            first_column: 0,
            last_line: 1,
            last_column: 0
        };
        if (this.options.ranges) {
            this.yylloc.range = [0,0];
        }
        this.offset = 0;
        return this;
    },

// consumes and returns one char from the input
input:function () {
        var ch = this._input[0];
        this.yytext += ch;
        this.yyleng++;
        this.offset++;
        this.match += ch;
        this.matched += ch;
        var lines = ch.match(/(?:\r\n?|\n).*/g);
        if (lines) {
            this.yylineno++;
            this.yylloc.last_line++;
        } else {
            this.yylloc.last_column++;
        }
        if (this.options.ranges) {
            this.yylloc.range[1]++;
        }

        this._input = this._input.slice(1);
        return ch;
    },

// unshifts one char (or a string) into the input
unput:function (ch) {
        var len = ch.length;
        var lines = ch.split(/(?:\r\n?|\n)/g);

        this._input = ch + this._input;
        this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
        //this.yyleng -= len;
        this.offset -= len;
        var oldLines = this.match.split(/(?:\r\n?|\n)/g);
        this.match = this.match.substr(0, this.match.length - 1);
        this.matched = this.matched.substr(0, this.matched.length - 1);

        if (lines.length - 1) {
            this.yylineno -= lines.length - 1;
        }
        var r = this.yylloc.range;

        this.yylloc = {
            first_line: this.yylloc.first_line,
            last_line: this.yylineno + 1,
            first_column: this.yylloc.first_column,
            last_column: lines ?
                (lines.length === oldLines.length ? this.yylloc.first_column : 0)
                 + oldLines[oldLines.length - lines.length].length - lines[0].length :
              this.yylloc.first_column - len
        };

        if (this.options.ranges) {
            this.yylloc.range = [r[0], r[0] + this.yyleng - len];
        }
        this.yyleng = this.yytext.length;
        return this;
    },

// When called from action, caches matched text and appends it on next action
more:function () {
        this._more = true;
        return this;
    },

// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.
reject:function () {
        if (this.options.backtrack_lexer) {
            this._backtrack = true;
        } else {
            return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), {
                text: "",
                token: null,
                line: this.yylineno
            });

        }
        return this;
    },

// retain first n characters of the match
less:function (n) {
        this.unput(this.match.slice(n));
    },

// displays already matched input, i.e. for error messages
pastInput:function () {
        var past = this.matched.substr(0, this.matched.length - this.match.length);
        return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
    },

// displays upcoming input, i.e. for error messages
upcomingInput:function () {
        var next = this.match;
        if (next.length < 20) {
            next += this._input.substr(0, 20-next.length);
        }
        return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
    },

// displays the character position where the lexing error occurred, i.e. for error messages
showPosition:function () {
        var pre = this.pastInput();
        var c = new Array(pre.length + 1).join("-");
        return pre + this.upcomingInput() + "\n" + c + "^";
    },

// test the lexed token: return FALSE when not a match, otherwise return token
test_match:function (match, indexed_rule) {
        var token,
            lines,
            backup;

        if (this.options.backtrack_lexer) {
            // save context
            backup = {
                yylineno: this.yylineno,
                yylloc: {
                    first_line: this.yylloc.first_line,
                    last_line: this.last_line,
                    first_column: this.yylloc.first_column,
                    last_column: this.yylloc.last_column
                },
                yytext: this.yytext,
                match: this.match,
                matches: this.matches,
                matched: this.matched,
                yyleng: this.yyleng,
                offset: this.offset,
                _more: this._more,
                _input: this._input,
                yy: this.yy,
                conditionStack: this.conditionStack.slice(0),
                done: this.done
            };
            if (this.options.ranges) {
                backup.yylloc.range = this.yylloc.range.slice(0);
            }
        }

        lines = match[0].match(/(?:\r\n?|\n).*/g);
        if (lines) {
            this.yylineno += lines.length;
        }
        this.yylloc = {
            first_line: this.yylloc.last_line,
            last_line: this.yylineno + 1,
            first_column: this.yylloc.last_column,
            last_column: lines ?
                         lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length :
                         this.yylloc.last_column + match[0].length
        };
        this.yytext += match[0];
        this.match += match[0];
        this.matches = match;
        this.yyleng = this.yytext.length;
        if (this.options.ranges) {
            this.yylloc.range = [this.offset, this.offset += this.yyleng];
        }
        this._more = false;
        this._backtrack = false;
        this._input = this._input.slice(match[0].length);
        this.matched += match[0];
        token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);
        if (this.done && this._input) {
            this.done = false;
        }
        if (token) {
            return token;
        } else if (this._backtrack) {
            // recover context
            for (var k in backup) {
                this[k] = backup[k];
            }
            return false; // rule action called reject() implying the next rule should be tested instead.
        }
        return false;
    },

// return next match in input
next:function () {
        if (this.done) {
            return this.EOF;
        }
        if (!this._input) {
            this.done = true;
        }

        var token,
            match,
            tempMatch,
            index;
        if (!this._more) {
            this.yytext = '';
            this.match = '';
        }
        var rules = this._currentRules();
        for (var i = 0; i < rules.length; i++) {
            tempMatch = this._input.match(this.rules[rules[i]]);
            if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
                match = tempMatch;
                index = i;
                if (this.options.backtrack_lexer) {
                    token = this.test_match(tempMatch, rules[i]);
                    if (token !== false) {
                        return token;
                    } else if (this._backtrack) {
                        match = false;
                        continue; // rule action called reject() implying a rule MISmatch.
                    } else {
                        // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
                        return false;
                    }
                } else if (!this.options.flex) {
                    break;
                }
            }
        }
        if (match) {
            token = this.test_match(match, rules[index]);
            if (token !== false) {
                return token;
            }
            // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
            return false;
        }
        if (this._input === "") {
            return this.EOF;
        } else {
            return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
                text: "",
                token: null,
                line: this.yylineno
            });
        }
    },

// return next match that has a token
lex:function lex() {
        var r = this.next();
        if (r) {
            return r;
        } else {
            return this.lex();
        }
    },

// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
begin:function begin(condition) {
        this.conditionStack.push(condition);
    },

// pop the previously active lexer condition state off the condition stack
popState:function popState() {
        var n = this.conditionStack.length - 1;
        if (n > 0) {
            return this.conditionStack.pop();
        } else {
            return this.conditionStack[0];
        }
    },

// produce the lexer rule set which is active for the currently active lexer condition state
_currentRules:function _currentRules() {
        if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {
            return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
        } else {
            return this.conditions["INITIAL"].rules;
        }
    },

// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available
topState:function topState(n) {
        n = this.conditionStack.length - 1 - Math.abs(n || 0);
        if (n >= 0) {
            return this.conditionStack[n];
        } else {
            return "INITIAL";
        }
    },

// alias for begin(condition)
pushState:function pushState(condition) {
        this.begin(condition);
    },

// return the number of states currently on the stack
stateStackSize:function stateStackSize() {
        return this.conditionStack.length;
    },
options: {},
performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START
/**/) {

var YYSTATE=YY_START;
switch($avoiding_name_collisions) {
case 0:return 4
// removed by dead control flow
{}
case 1:return 14
// removed by dead control flow
{}
case 2:return 12
// removed by dead control flow
{}
case 3:return 15
// removed by dead control flow
{}
case 4:return 16
// removed by dead control flow
{}
case 5:return 22
// removed by dead control flow
{}
case 6:return 24
// removed by dead control flow
{}
case 7:return 28
// removed by dead control flow
{}
case 8:return 30
// removed by dead control flow
{}
case 9:return 18
// removed by dead control flow
{}
case 10:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 32;
// removed by dead control flow
{}
case 11:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 33;
// removed by dead control flow
{}
case 12:return 17
// removed by dead control flow
{}
case 13:return 31
// removed by dead control flow
{}
}
},
rules: [/^(?:\$)/,/^(?:\.\.)/,/^(?:\.)/,/^(?:\*)/,/^(?:[a-zA-Z_]+[a-zA-Z0-9_]*)/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?:((-?(?:0|[1-9][0-9]*)))?\:((-?(?:0|[1-9][0-9]*)))?(\:((-?(?:0|[1-9][0-9]*)))?)?)/,/^(?:(-?(?:0|[1-9][0-9]*)))/,/^(?:"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*")/,/^(?:'(?:\\['bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^'\\])*')/,/^(?:\(.+?\)(?=\]))/,/^(?:\?\(.+?\)(?=\]))/],
conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}}
};
return lexer;
})();
parser.lexer = lexer;
function Parser () {
  this.yy = {};
}
Parser.prototype = parser;parser.Parser = Parser;
return new Parser;
})();


if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = parser;
exports.Parser = parser.Parser;
exports.parse = function () { return parser.parse.apply(parser, arguments); };
exports.main = function commonjsMain(args) {
    if (!args[1]) {
        console.log('Usage: '+args[0]+' FILE');
        process.exit(1);
    }
    var source = require('fs').readFileSync(require('path').normalize(args[1]), "utf8");
    return exports.parser.parse(source);
};
if (typeof module !== 'undefined' && require.main === module) {
  exports.main(process.argv.slice(1));
}
}

}).call(this,require('_process'))
},{"_process":14,"fs":12,"path":13}],2:[function(require,module,exports){
module.exports = {
  identifier: "[a-zA-Z_]+[a-zA-Z0-9_]*",
  integer: "-?(?:0|[1-9][0-9]*)",
  qq_string: "\"(?:\\\\[\"bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\"\\\\])*\"",
  q_string: "'(?:\\\\[\'bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\'\\\\])*'"
};

},{}],3:[function(require,module,exports){
var dict = require('./dict');
var fs = require('fs');
var grammar = {

    lex: {

        macros: {
            esc: "\\\\",
            int: dict.integer
        },

        rules: [
            ["\\$", "return 'DOLLAR'"],
            ["\\.\\.", "return 'DOT_DOT'"],
            ["\\.", "return 'DOT'"],
            ["\\*", "return 'STAR'"],
            [dict.identifier, "return 'IDENTIFIER'"],
            ["\\[", "return '['"],
            ["\\]", "return ']'"],
            [",", "return ','"],
            ["({int})?\\:({int})?(\\:({int})?)?", "return 'ARRAY_SLICE'"],
            ["{int}", "return 'INTEGER'"],
            [dict.qq_string, "yytext = yytext.substr(1,yyleng-2); return 'QQ_STRING';"],
            [dict.q_string, "yytext = yytext.substr(1,yyleng-2); return 'Q_STRING';"],
            ["\\(.+?\\)(?=\\])", "return 'SCRIPT_EXPRESSION'"],
            ["\\?\\(.+?\\)(?=\\])", "return 'FILTER_EXPRESSION'"]
        ]
    },

    start: "JSON_PATH",

    bnf: {

        JSON_PATH: [
                [ 'DOLLAR',                 'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()' ],
                [ 'DOLLAR PATH_COMPONENTS', 'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()' ],
                [ 'LEADING_CHILD_MEMBER_EXPRESSION',                 'yy.ast.unshift(); return yy.ast.yield()' ],
                [ 'LEADING_CHILD_MEMBER_EXPRESSION PATH_COMPONENTS', 'yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $1 }}); yy.ast.unshift(); return yy.ast.yield()' ] ],

        PATH_COMPONENTS: [
                [ 'PATH_COMPONENT',                 '' ],
                [ 'PATH_COMPONENTS PATH_COMPONENT', '' ] ],

        PATH_COMPONENT: [
                [ 'MEMBER_COMPONENT',    'yy.ast.set({ operation: "member" }); yy.ast.push()' ],
                [ 'SUBSCRIPT_COMPONENT', 'yy.ast.set({ operation: "subscript" }); yy.ast.push() ' ] ],

        MEMBER_COMPONENT: [
                [ 'CHILD_MEMBER_COMPONENT',      'yy.ast.set({ scope: "child" })' ],
                [ 'DESCENDANT_MEMBER_COMPONENT', 'yy.ast.set({ scope: "descendant" })' ] ],

        CHILD_MEMBER_COMPONENT: [
                [ 'DOT MEMBER_EXPRESSION', '' ] ],

        LEADING_CHILD_MEMBER_EXPRESSION: [
                [ 'MEMBER_EXPRESSION', 'yy.ast.set({ scope: "child", operation: "member" })' ] ],

        DESCENDANT_MEMBER_COMPONENT: [
                [ 'DOT_DOT MEMBER_EXPRESSION', '' ] ],

        MEMBER_EXPRESSION: [
                [ 'STAR',              'yy.ast.set({ expression: { type: "wildcard", value: $1 } })' ],
                [ 'IDENTIFIER',        'yy.ast.set({ expression: { type: "identifier", value: $1 } })' ],
                [ 'SCRIPT_EXPRESSION', 'yy.ast.set({ expression: { type: "script_expression", value: $1 } })' ],
                [ 'INTEGER',           'yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($1) } })' ],
                [ 'END',               '' ] ],

        SUBSCRIPT_COMPONENT: [
                [ 'CHILD_SUBSCRIPT_COMPONENT',      'yy.ast.set({ scope: "child" })' ],
                [ 'DESCENDANT_SUBSCRIPT_COMPONENT', 'yy.ast.set({ scope: "descendant" })' ] ],

        CHILD_SUBSCRIPT_COMPONENT: [
                [ '[ SUBSCRIPT ]', '' ] ],

        DESCENDANT_SUBSCRIPT_COMPONENT: [
                [ 'DOT_DOT [ SUBSCRIPT ]', '' ] ],

        SUBSCRIPT: [
                [ 'SUBSCRIPT_EXPRESSION', '' ],
                [ 'SUBSCRIPT_EXPRESSION_LIST', '$1.length > 1? yy.ast.set({ expression: { type: "union", value: $1 } }) : $$ = $1' ] ],

        SUBSCRIPT_EXPRESSION_LIST: [
                [ 'SUBSCRIPT_EXPRESSION_LISTABLE', '$$ = [$1]'],
                [ 'SUBSCRIPT_EXPRESSION_LIST , SUBSCRIPT_EXPRESSION_LISTABLE', '$$ = $1.concat($3)' ] ],

        SUBSCRIPT_EXPRESSION_LISTABLE: [
                [ 'INTEGER',           '$$ = { expression: { type: "numeric_literal", value: parseInt($1) } }; yy.ast.set($$)' ],
                [ 'STRING_LITERAL',    '$$ = { expression: { type: "string_literal", value: $1 } }; yy.ast.set($$)' ],
                [ 'ARRAY_SLICE',       '$$ = { expression: { type: "slice", value: $1 } }; yy.ast.set($$)' ] ],

        SUBSCRIPT_EXPRESSION: [
                [ 'STAR',              '$$ = { expression: { type: "wildcard", value: $1 } }; yy.ast.set($$)' ],
                [ 'SCRIPT_EXPRESSION', '$$ = { expression: { type: "script_expression", value: $1 } }; yy.ast.set($$)' ],
                [ 'FILTER_EXPRESSION', '$$ = { expression: { type: "filter_expression", value: $1 } }; yy.ast.set($$)' ] ],

        STRING_LITERAL: [
                [ 'QQ_STRING', "$$ = $1" ],
                [ 'Q_STRING',  "$$ = $1" ] ]
    }
};
if (fs.readFileSync) {
  grammar.moduleInclude = fs.readFileSync(require.resolve("../include/module.js"));
  grammar.actionInclude = fs.readFileSync(require.resolve("../include/action.js"));
}

module.exports = grammar;

},{"./dict":2,"fs":12}],4:[function(require,module,exports){
var aesprim = require('./aesprim');
var slice = require('./slice');
var _evaluate = require('static-eval');
var _uniq = require('underscore').uniq;

var Handlers = function() {
  return this.initialize.apply(this, arguments);
}

Handlers.prototype.initialize = function() {
  this.traverse = traverser(true);
  this.descend = traverser();
}

Handlers.prototype.keys = Object.keys;

Handlers.prototype.resolve = function(component) {

  var key = [ component.operation, component.scope, component.expression.type ].join('-');
  var method = this._fns[key];

  if (!method) throw new Error("couldn't resolve key: " + key);
  return method.bind(this);
};

Handlers.prototype.register = function(key, handler) {

  if (!handler instanceof Function) {
    throw new Error("handler must be a function");
  }

  this._fns[key] = handler;
};

Handlers.prototype._fns = {

  'member-child-identifier': function(component, partial) {
    var key = component.expression.value;
    var value = partial.value;
    if (value instanceof Object && key in value) {
      return [ { value: value[key], path: partial.path.concat(key) } ]
    }
  },

  'member-descendant-identifier':
    _traverse(function(key, value, ref) { return key == ref }),

  'subscript-child-numeric_literal':
    _descend(function(key, value, ref) { return key === ref }),

  'member-child-numeric_literal':
    _descend(function(key, value, ref) { return String(key) === String(ref) }),

  'subscript-descendant-numeric_literal':
    _traverse(function(key, value, ref) { return key === ref }),

  'member-child-wildcard':
    _descend(function() { return true }),

  'member-descendant-wildcard':
    _traverse(function() { return true }),

  'subscript-descendant-wildcard':
    _traverse(function() { return true }),

  'subscript-child-wildcard':
    _descend(function() { return true }),

  'subscript-child-slice': function(component, partial) {
    if (is_array(partial.value)) {
      var args = component.expression.value.split(':').map(_parse_nullable_int);
      var values = partial.value.map(function(v, i) { return { value: v, path: partial.path.concat(i) } });
      return slice.apply(null, [values].concat(args));
    }
  },

  'subscript-child-union': function(component, partial) {
    var results = [];
    component.expression.value.forEach(function(component) {
      var _component = { operation: 'subscript', scope: 'child', expression: component.expression };
      var handler = this.resolve(_component);
      var _results = handler(_component, partial);
      if (_results) {
        results = results.concat(_results);
      }
    }, this);

    return unique(results);
  },

  'subscript-descendant-union': function(component, partial, count) {

    var jp = require('..');
    var self = this;

    var results = [];
    var nodes = jp.nodes(partial, '$..*').slice(1);

    nodes.forEach(function(node) {
      if (results.length >= count) return;
      component.expression.value.forEach(function(component) {
        var _component = { operation: 'subscript', scope: 'child', expression: component.expression };
        var handler = self.resolve(_component);
        var _results = handler(_component, node);
        results = results.concat(_results);
      });
    });

    return unique(results);
  },

  'subscript-child-filter_expression': function(component, partial, count) {

    // slice out the expression from ?(expression)
    var src = component.expression.value.slice(2, -1);
    var ast = aesprim.parse(src).body[0].expression;

    var passable = function(key, value) {
      return evaluate(ast, { '@': value });
    }

    return this.descend(partial, null, passable, count);

  },

  'subscript-descendant-filter_expression': function(component, partial, count) {

    // slice out the expression from ?(expression)
    var src = component.expression.value.slice(2, -1);
    var ast = aesprim.parse(src).body[0].expression;

    var passable = function(key, value) {
      return evaluate(ast, { '@': value });
    }

    return this.traverse(partial, null, passable, count);
  },

  'subscript-child-script_expression': function(component, partial) {
    var exp = component.expression.value.slice(1, -1);
    return eval_recurse(partial, exp, '$[{{value}}]');
  },

  'member-child-script_expression': function(component, partial) {
    var exp = component.expression.value.slice(1, -1);
    return eval_recurse(partial, exp, '$.{{value}}');
  },

  'member-descendant-script_expression': function(component, partial) {
    var exp = component.expression.value.slice(1, -1);
    return eval_recurse(partial, exp, '$..value');
  }
};

Handlers.prototype._fns['subscript-child-string_literal'] =
	Handlers.prototype._fns['member-child-identifier'];

Handlers.prototype._fns['member-descendant-numeric_literal'] =
    Handlers.prototype._fns['subscript-descendant-string_literal'] =
    Handlers.prototype._fns['member-descendant-identifier'];

function eval_recurse(partial, src, template) {

  var jp = require('./index');
  var ast = aesprim.parse(src).body[0].expression;
  var value = evaluate(ast, { '@': partial.value });
  var path = template.replace(/\{\{\s*value\s*\}\}/g, value);

  var results = jp.nodes(partial.value, path);
  results.forEach(function(r) {
    r.path = partial.path.concat(r.path.slice(1));
  });

  return results;
}

function is_array(val) {
  return Array.isArray(val);
}

function is_object(val) {
  // is this a non-array, non-null object?
  return val && !(val instanceof Array) && val instanceof Object;
}

function traverser(recurse) {

  return function(partial, ref, passable, count) {

    var value = partial.value;
    var path = partial.path;

    var results = [];

    var descend = function(value, path) {

      if (is_array(value)) {
        value.forEach(function(element, index) {
          if (results.length >= count) { return }
          if (passable(index, element, ref)) {
            results.push({ path: path.concat(index), value: element });
          }
        });
        value.forEach(function(element, index) {
          if (results.length >= count) { return }
          if (recurse) {
            descend(element, path.concat(index));
          }
        });
      } else if (is_object(value)) {
        this.keys(value).forEach(function(k) {
          if (results.length >= count) { return }
          if (passable(k, value[k], ref)) {
            results.push({ path: path.concat(k), value: value[k] });
          }
        })
        this.keys(value).forEach(function(k) {
          if (results.length >= count) { return }
          if (recurse) {
            descend(value[k], path.concat(k));
          }
        });
      }
    }.bind(this);
    descend(value, path);
    return results;
  }
}

function _descend(passable) {
  return function(component, partial, count) {
    return this.descend(partial, component.expression.value, passable, count);
  }
}

function _traverse(passable) {
  return function(component, partial, count) {
    return this.traverse(partial, component.expression.value, passable, count);
  }
}

function evaluate() {
  try { return _evaluate.apply(this, arguments) }
  catch (e) { }
}

function unique(results) {
  results = results.filter(function(d) { return d })
  return _uniq(
    results,
    function(r) { return r.path.map(function(c) { return String(c).replace('-', '--') }).join('-') }
  );
}

function _parse_nullable_int(val) {
  var sval = String(val);
  return sval.match(/^-?[0-9]+$/) ? parseInt(sval) : null;
}

module.exports = Handlers;

},{"..":"jsonpath","./aesprim":"./aesprim","./index":5,"./slice":7,"static-eval":15,"underscore":12}],5:[function(require,module,exports){
var assert = require('assert');
var dict = require('./dict');
var Parser = require('./parser');
var Handlers = require('./handlers');

var JSONPath = function() {
  this.initialize.apply(this, arguments);
};

JSONPath.prototype.initialize = function() {
  this.parser = new Parser();
  this.handlers = new Handlers();
};

JSONPath.prototype.parse = function(string) {
  assert.ok(_is_string(string), "we need a path");
  return this.parser.parse(string);
};

JSONPath.prototype.parent = function(obj, string) {

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(string, "we need a path");

  var node = this.nodes(obj, string)[0];
  var key = node.path.pop(); /* jshint unused:false */
  return this.value(obj, node.path);
}

JSONPath.prototype.apply = function(obj, string, fn) {

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(string, "we need a path");
  assert.equal(typeof fn, "function", "fn needs to be function")

  var nodes = this.nodes(obj, string).sort(function(a, b) {
    // sort nodes so we apply from the bottom up
    return b.path.length - a.path.length;
  });

  nodes.forEach(function(node) {
    var key = node.path.pop();
    var parent = this.value(obj, this.stringify(node.path));
    var val = node.value = fn.call(obj, parent[key]);
    parent[key] = val;
  }, this);

  return nodes;
}

JSONPath.prototype.value = function(obj, path, value) {

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(path, "we need a path");

  if (arguments.length >= 3) {
    var node = this.nodes(obj, path).shift();
    if (!node) return this._vivify(obj, path, value);
    var key = node.path.slice(-1).shift();
    var parent = this.parent(obj, this.stringify(node.path));
    parent[key] = value;
  }
  return this.query(obj, this.stringify(path), 1).shift();
}

JSONPath.prototype._vivify = function(obj, string, value) {

  var self = this;

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(string, "we need a path");

  var path = this.parser.parse(string)
    .map(function(component) { return component.expression.value });

  var setValue = function(path, value) {
    var key = path.pop();
    var node = self.value(obj, path);
    if (!node) {
      setValue(path.concat(), typeof key === 'string' ? {} : []);
      node = self.value(obj, path);
    }
    node[key] = value;
  }
  setValue(path, value);
  return this.query(obj, string)[0];
}

JSONPath.prototype.query = function(obj, string, count) {

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(_is_string(string), "we need a path");

  var results = this.nodes(obj, string, count)
    .map(function(r) { return r.value });

  return results;
};

JSONPath.prototype.paths = function(obj, string, count) {

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(string, "we need a path");

  var results = this.nodes(obj, string, count)
    .map(function(r) { return r.path });

  return results;
};

JSONPath.prototype.nodes = function(obj, string, count) {

  assert.ok(obj instanceof Object, "obj needs to be an object");
  assert.ok(string, "we need a path");

  if (count === 0) return [];

  var path = this.parser.parse(string);
  var handlers = this.handlers;

  var partials = [ { path: ['$'], value: obj } ];
  var matches = [];

  if (path.length && path[0].expression.type == 'root') path.shift();

  if (!path.length) return partials;

  path.forEach(function(component, index) {

    if (matches.length >= count) return;
    var handler = handlers.resolve(component);
    var _partials = [];

    partials.forEach(function(p) {

      if (matches.length >= count) return;
      var results = handler(component, p, count);

      if (index == path.length - 1) {
        // if we're through the components we're done
        matches = matches.concat(results || []);
      } else {
        // otherwise accumulate and carry on through
        _partials = _partials.concat(results || []);
      }
    });

    partials = _partials;

  });

  return count ? matches.slice(0, count) : matches;
};

JSONPath.prototype.stringify = function(path) {

  assert.ok(path, "we need a path");

  var string = '$';

  var templates = {
    'descendant-member': '..{{value}}',
    'child-member': '.{{value}}',
    'descendant-subscript': '..[{{value}}]',
    'child-subscript': '[{{value}}]'
  };

  path = this._normalize(path);

  path.forEach(function(component) {

    if (component.expression.type == 'root') return;

    var key = [component.scope, component.operation].join('-');
    var template = templates[key];
    var value;

    if (component.expression.type == 'string_literal') {
      value = JSON.stringify(component.expression.value)
    } else {
      value = component.expression.value;
    }

    if (!template) throw new Error("couldn't find template " + key);

    string += template.replace(/{{value}}/, value);
  });

  return string;
}

JSONPath.prototype._normalize = function(path) {

  assert.ok(path, "we need a path");

  if (typeof path == "string") {

    return this.parser.parse(path);

  } else if (Array.isArray(path) && typeof path[0] == "string") {

    var _path = [ { expression: { type: "root", value: "$" } } ];

    path.forEach(function(component, index) {

      if (component == '$' && index === 0) return;

      if (typeof component == "string" && component.match("^" + dict.identifier + "$")) {

        _path.push({
          operation: 'member',
          scope: 'child',
          expression: { value: component, type: 'identifier' }
        });

      } else {

        var type = typeof component == "number" ?
          'numeric_literal' : 'string_literal';

        _path.push({
          operation: 'subscript',
          scope: 'child',
          expression: { value: component, type: type }
        });
      }
    });

    return _path;

  } else if (Array.isArray(path) && typeof path[0] == "object") {

    return path
  }

  throw new Error("couldn't understand path " + path);
}

function _is_string(obj) {
  return Object.prototype.toString.call(obj) == '[object String]';
}

JSONPath.Handlers = Handlers;
JSONPath.Parser = Parser;

var instance = new JSONPath;
instance.JSONPath = JSONPath;

module.exports = instance;

},{"./dict":2,"./handlers":4,"./parser":6,"assert":8}],6:[function(require,module,exports){
var grammar = require('./grammar');
var gparser = require('../generated/parser');

var Parser = function() {

  var parser = new gparser.Parser();

  var _parseError = parser.parseError;
  parser.yy.parseError = function() {
    if (parser.yy.ast) {
      parser.yy.ast.initialize();
    }
    _parseError.apply(parser, arguments);
  }

  return parser;

};

Parser.grammar = grammar;
module.exports = Parser;

},{"../generated/parser":1,"./grammar":3}],7:[function(require,module,exports){
module.exports = function(arr, start, end, step) {

  if (typeof start == 'string') throw new Error("start cannot be a string");
  if (typeof end == 'string') throw new Error("end cannot be a string");
  if (typeof step == 'string') throw new Error("step cannot be a string");

  var len = arr.length;

  if (step === 0) throw new Error("step cannot be zero");
  step = step ? integer(step) : 1;

  // normalize negative values
  start = start < 0 ? len + start : start;
  end = end < 0 ? len + end : end;

  // default extents to extents
  start = integer(start === 0 ? 0 : !start ? (step > 0 ? 0 : len - 1) : start);
  end = integer(end === 0 ? 0 : !end ? (step > 0 ? len : -1) : end);

  // clamp extents
  start = step > 0 ? Math.max(0, start) : Math.min(len, start);
  end = step > 0 ? Math.min(end, len) : Math.max(-1, end);

  // return empty if extents are backwards
  if (step > 0 && end <= start) return [];
  if (step < 0 && start <= end) return [];

  var result = [];

  for (var i = start; i != end; i += step) {
    if ((step < 0 && i <= end) || (step > 0 && i >= end)) break;
    result.push(arr[i]);
  }

  return result;
}

function integer(val) {
  return String(val).match(/^[0-9]+$/) ? parseInt(val) :
    Number.isFinite(val) ? parseInt(val, 10) : 0;
}

},{}],8:[function(require,module,exports){
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 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.

// when used in node, this will actually load the util module we depend on
// versus loading the builtin util module as happens otherwise
// this is a bug in node module loading as far as I am concerned
var util = require('util/');

var pSlice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;

// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.

var assert = module.exports = ok;

// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })

assert.AssertionError = function AssertionError(options) {
  this.name = 'AssertionError';
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  if (options.message) {
    this.message = options.message;
    this.generatedMessage = false;
  } else {
    this.message = getMessage(this);
    this.generatedMessage = true;
  }
  var stackStartFunction = options.stackStartFunction || fail;

  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, stackStartFunction);
  }
  else {
    // non v8 browsers so we can have a stacktrace
    var err = new Error();
    if (err.stack) {
      var out = err.stack;

      // try to strip useless frames
      var fn_name = stackStartFunction.name;
      var idx = out.indexOf('\n' + fn_name);
      if (idx >= 0) {
        // once we have located the function frame
        // we need to strip out everything before it (and its line)
        var next_line = out.indexOf('\n', idx + 1);
        out = out.substring(next_line + 1);
      }

      this.stack = out;
    }
  }
};

// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);

function replacer(key, value) {
  if (util.isUndefined(value)) {
    return '' + value;
  }
  if (util.isNumber(value) && !isFinite(value)) {
    return value.toString();
  }
  if (util.isFunction(value) || util.isRegExp(value)) {
    return value.toString();
  }
  return value;
}

function truncate(s, n) {
  if (util.isString(s)) {
    return s.length < n ? s : s.slice(0, n);
  } else {
    return s;
  }
}

function getMessage(self) {
  return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
         self.operator + ' ' +
         truncate(JSON.stringify(self.expected, replacer), 128);
}

// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.

// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided.  All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);

assert.equal = function equal(actual, expected, message) {
  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};

// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);

assert.notEqual = function notEqual(actual, expected, message) {
  if (actual == expected) {
    fail(actual, expected, message, '!=', assert.notEqual);
  }
};

// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);

assert.deepEqual = function deepEqual(actual, expected, message) {
  if (!_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  }
};

function _deepEqual(actual, expected) {
  // 7.1. All identical values are equivalent, as determined by ===.
  if (actual === expected) {
    return true;

  } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
    if (actual.length != expected.length) return false;

    for (var i = 0; i < actual.length; i++) {
      if (actual[i] !== expected[i]) return false;
    }

    return true;

  // 7.2. If the expected value is a Date object, the actual value is
  // equivalent if it is also a Date object that refers to the same time.
  } else if (util.isDate(actual) && util.isDate(expected)) {
    return actual.getTime() === expected.getTime();

  // 7.3 If the expected value is a RegExp object, the actual value is
  // equivalent if it is also a RegExp object with the same source and
  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
    return actual.source === expected.source &&
           actual.global === expected.global &&
           actual.multiline === expected.multiline &&
           actual.lastIndex === expected.lastIndex &&
           actual.ignoreCase === expected.ignoreCase;

  // 7.4. Other pairs that do not both pass typeof value == 'object',
  // equivalence is determined by ==.
  } else if (!util.isObject(actual) && !util.isObject(expected)) {
    return actual == expected;

  // 7.5 For all other Object pairs, including Array objects, equivalence is
  // determined by having the same number of owned properties (as verified
  // with Object.prototype.hasOwnProperty.call), the same set of keys
  // (although not necessarily the same order), equivalent values for every
  // corresponding key, and an identical 'prototype' property. Note: this
  // accounts for both named and indexed properties on Arrays.
  } else {
    return objEquiv(actual, expected);
  }
}

function isArguments(object) {
  return Object.prototype.toString.call(object) == '[object Arguments]';
}

function objEquiv(a, b) {
  if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
    return false;
  // an identical 'prototype' property.
  if (a.prototype !== b.prototype) return false;
  // if one is a primitive, the other must be same
  if (util.isPrimitive(a) || util.isPrimitive(b)) {
    return a === b;
  }
  var aIsArgs = isArguments(a),
      bIsArgs = isArguments(b);
  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
    return false;
  if (aIsArgs) {
    a = pSlice.call(a);
    b = pSlice.call(b);
    return _deepEqual(a, b);
  }
  var ka = objectKeys(a),
      kb = objectKeys(b),
      key, i;
  // having the same number of owned properties (keys incorporates
  // hasOwnProperty)
  if (ka.length != kb.length)
    return false;
  //the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  //~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] != kb[i])
      return false;
  }
  //equivalent values for every corresponding key, and
  //~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!_deepEqual(a[key], b[key])) return false;
  }
  return true;
}

// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);

assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  if (_deepEqual(actual, expected)) {
    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  }
};

// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);

assert.strictEqual = function strictEqual(actual, expected, message) {
  if (actual !== expected) {
    fail(actual, expected, message, '===', assert.strictEqual);
  }
};

// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);

assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (actual === expected) {
    fail(actual, expected, message, '!==', assert.notStrictEqual);
  }
};

function expectedException(actual, expected) {
  if (!actual || !expected) {
    return false;
  }

  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
    return expected.test(actual);
  } else if (actual instanceof expected) {
    return true;
  } else if (expected.call({}, actual) === true) {
    return true;
  }

  return false;
}

function _throws(shouldThrow, block, expected, message) {
  var actual;

  if (util.isString(expected)) {
    message = expected;
    expected = null;
  }

  try {
    block();
  } catch (e) {
    actual = e;
  }

  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
            (message ? ' ' + message : '.');

  if (shouldThrow && !actual) {
    fail(actual, expected, 'Missing expected exception' + message);
  }

  if (!shouldThrow && expectedException(actual, expected)) {
    fail(actual, expected, 'Got unwanted exception' + message);
  }

  if ((shouldThrow && actual && expected &&
      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
    throw actual;
  }
}

// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);

assert.throws = function(block, /*optional*/error, /*optional*/message) {
  _throws.apply(this, [true].concat(pSlice.call(arguments)));
};

// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
  _throws.apply(this, [false].concat(pSlice.call(arguments)));
};

assert.ifError = function(err) { if (err) {throw err;}};

var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    if (hasOwn.call(obj, key)) keys.push(key);
  }
  return keys;
};

},{"util/":11}],9:[function(require,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
  }
}

},{}],10:[function(require,module,exports){
module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}
},{}],11:[function(require,module,exports){
(function (process,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.

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) {
  // Allow for deprecating things in the process of starting up.
  if (isUndefined(global.process)) {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  if (process.noDeprecation === true) {
    return fn;
  }

  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 = process.env.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 = require('./support/isBuffer');

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 = require('inherits');

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);
}

}).call(this,require('_process'),typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":10,"_process":14,"inherits":9}],12:[function(require,module,exports){

},{}],13:[function(require,module,exports){
(function (process){
// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
// backported and transplited with Babel, with backwards-compat fixes

// 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.

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === '.') {
      parts.splice(i, 1);
    } else if (last === '..') {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift('..');
    }
  }

  return parts;
}

// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
  var resolvedPath = '',
      resolvedAbsolute = false;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path = (i >= 0) ? arguments[i] : process.cwd();

    // Skip empty and invalid entries
    if (typeof path !== 'string') {
      throw new TypeError('Arguments to path.resolve must be strings');
    } else if (!path) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charAt(0) === '/';
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
    return !!p;
  }), !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
// posix version
exports.normalize = function(path) {
  var isAbsolute = exports.isAbsolute(path),
      trailingSlash = substr(path, -1) === '/';

  // Normalize the path
  path = normalizeArray(filter(path.split('/'), function(p) {
    return !!p;
  }), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  if (path && trailingSlash) {
    path += '/';
  }

  return (isAbsolute ? '/' : '') + path;
};

// posix version
exports.isAbsolute = function(path) {
  return path.charAt(0) === '/';
};

// posix version
exports.join = function() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return exports.normalize(filter(paths, function(p, index) {
    if (typeof p !== 'string') {
      throw new TypeError('Arguments to path.join must be strings');
    }
    return p;
  }).join('/'));
};


// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
  from = exports.resolve(from).substr(1);
  to = exports.resolve(to).substr(1);

  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== '') break;
    }

    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== '') break;
    }

    if (start > end) return [];
    return arr.slice(start, end - start + 1);
  }

  var fromParts = trim(from.split('/'));
  var toParts = trim(to.split('/'));

  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }

  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push('..');
  }

  outputParts = outputParts.concat(toParts.slice(samePartsLength));

  return outputParts.join('/');
};

exports.sep = '/';
exports.delimiter = ':';

exports.dirname = function (path) {
  if (typeof path !== 'string') path = path + '';
  if (path.length === 0) return '.';
  var code = path.charCodeAt(0);
  var hasRoot = code === 47 /*/*/;
  var end = -1;
  var matchedSlash = true;
  for (var i = path.length - 1; i >= 1; --i) {
    code = path.charCodeAt(i);
    if (code === 47 /*/*/) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
      // We saw the first non-path separator
      matchedSlash = false;
    }
  }

  if (end === -1) return hasRoot ? '/' : '.';
  if (hasRoot && end === 1) {
    // return '//';
    // Backwards-compat fix:
    return '/';
  }
  return path.slice(0, end);
};

function basename(path) {
  if (typeof path !== 'string') path = path + '';

  var start = 0;
  var end = -1;
  var matchedSlash = true;
  var i;

  for (i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === 47 /*/*/) {
        // If we reached a path separator that was not part of a set of path
        // separators at the end of the string, stop now
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
      // We saw the first non-path separator, mark this as the end of our
      // path component
      matchedSlash = false;
      end = i + 1;
    }
  }

  if (end === -1) return '';
  return path.slice(start, end);
}

// Uses a mixed approach for backwards-compatibility, as ext behavior changed
// in new Node.js versions, so only basename() above is backported here
exports.basename = function (path, ext) {
  var f = basename(path);
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
};

exports.extname = function (path) {
  if (typeof path !== 'string') path = path + '';
  var startDot = -1;
  var startPart = 0;
  var end = -1;
  var matchedSlash = true;
  // Track the state of characters (if any) we see before our first dot and
  // after any path separator we find
  var preDotState = 0;
  for (var i = path.length - 1; i >= 0; --i) {
    var code = path.charCodeAt(i);
    if (code === 47 /*/*/) {
        // If we reached a path separator that was not part of a set of path
        // separators at the end of the string, stop now
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
    if (end === -1) {
      // We saw the first non-path separator, mark this as the end of our
      // extension
      matchedSlash = false;
      end = i + 1;
    }
    if (code === 46 /*.*/) {
        // If this is our first dot, mark it as the start of our extension
        if (startDot === -1)
          startDot = i;
        else if (preDotState !== 1)
          preDotState = 1;
    } else if (startDot !== -1) {
      // We saw a non-dot and non-path separator before our dot, so we should
      // have a good chance at having a non-empty extension
      preDotState = -1;
    }
  }

  if (startDot === -1 || end === -1 ||
      // We saw a non-dot character immediately before the dot
      preDotState === 0 ||
      // The (right-most) trimmed path component is exactly '..'
      preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return '';
  }
  return path.slice(startDot, end);
};

function filter (xs, f) {
    if (xs.filter) return xs.filter(f);
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        if (f(xs[i], i, xs)) res.push(xs[i]);
    }
    return res;
}

// String.prototype.substr - negative index don't work in IE8
var substr =  true
    ? function (str, start, len) { return str.substr(start, len) }
    : 0
;

}).call(this,require('_process'))
},{"_process":14}],14:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};

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

var cachedSetTimeout;
var cachedClearTimeout;

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


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



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

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

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

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

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

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

function noop() {}

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

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

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

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

},{}],15:[function(require,module,exports){
var unparse = require('escodegen').generate;

module.exports = function (ast, vars) {
    if (!vars) vars = {};
    var FAIL = {};
    
    var result = (function walk (node, scopeVars) {
        if (node.type === 'Literal') {
            return node.value;
        }
        else if (node.type === 'UnaryExpression'){
            var val = walk(node.argument)
            if (node.operator === '+') return +val
            if (node.operator === '-') return -val
            if (node.operator === '~') return ~val
            if (node.operator === '!') return !val
            return FAIL
        }
        else if (node.type === 'ArrayExpression') {
            var xs = [];
            for (var i = 0, l = node.elements.length; i < l; i++) {
                var x = walk(node.elements[i]);
                if (x === FAIL) return FAIL;
                xs.push(x);
            }
            return xs;
        }
        else if (node.type === 'ObjectExpression') {
            var obj = {};
            for (var i = 0; i < node.properties.length; i++) {
                var prop = node.properties[i];
                var value = prop.value === null
                    ? prop.value
                    : walk(prop.value)
                ;
                if (value === FAIL) return FAIL;
                obj[prop.key.value || prop.key.name] = value;
            }
            return obj;
        }
        else if (node.type === 'BinaryExpression' ||
                 node.type === 'LogicalExpression') {
            var l = walk(node.left);
            if (l === FAIL) return FAIL;
            var r = walk(node.right);
            if (r === FAIL) return FAIL;
            
            var op = node.operator;
            if (op === '==') return l == r;
            if (op === '===') return l === r;
            if (op === '!=') return l != r;
            if (op === '!==') return l !== r;
            if (op === '+') return l + r;
            if (op === '-') return l - r;
            if (op === '*') return l * r;
            if (op === '/') return l / r;
            if (op === '%') return l % r;
            if (op === '<') return l < r;
            if (op === '<=') return l <= r;
            if (op === '>') return l > r;
            if (op === '>=') return l >= r;
            if (op === '|') return l | r;
            if (op === '&') return l & r;
            if (op === '^') return l ^ r;
            if (op === '&&') return l && r;
            if (op === '||') return l || r;
            
            return FAIL;
        }
        else if (node.type === 'Identifier') {
            if ({}.hasOwnProperty.call(vars, node.name)) {
                return vars[node.name];
            }
            else return FAIL;
        }
        else if (node.type === 'ThisExpression') {
            if ({}.hasOwnProperty.call(vars, 'this')) {
                return vars['this'];
            }
            else return FAIL;
        }
        else if (node.type === 'CallExpression') {
            var callee = walk(node.callee);
            if (callee === FAIL) return FAIL;
            if (typeof callee !== 'function') return FAIL;
            
            var ctx = node.callee.object ? walk(node.callee.object) : FAIL;
            if (ctx === FAIL) ctx = null;

            var args = [];
            for (var i = 0, l = node.arguments.length; i < l; i++) {
                var x = walk(node.arguments[i]);
                if (x === FAIL) return FAIL;
                args.push(x);
            }
            return callee.apply(ctx, args);
        }
        else if (node.type === 'MemberExpression') {
            var obj = walk(node.object);
            // do not allow access to methods on Function 
            if((obj === FAIL) || (typeof obj == 'function')){
                return FAIL;
            }
            if (node.property.type === 'Identifier') {
                return obj[node.property.name];
            }
            var prop = walk(node.property);
            if (prop === FAIL) return FAIL;
            return obj[prop];
        }
        else if (node.type === 'ConditionalExpression') {
            var val = walk(node.test)
            if (val === FAIL) return FAIL;
            return val ? walk(node.consequent) : walk(node.alternate)
        }
        else if (node.type === 'ExpressionStatement') {
            var val = walk(node.expression)
            if (val === FAIL) return FAIL;
            return val;
        }
        else if (node.type === 'ReturnStatement') {
            return walk(node.argument)
        }
        else if (node.type === 'FunctionExpression') {
            
            var bodies = node.body.body;
            
            // Create a "scope" for our arguments
            var oldVars = {};
            Object.keys(vars).forEach(function(element){
                oldVars[element] = vars[element];
            })

            for(var i=0; i<node.params.length; i++){
                var key = node.params[i];
                if(key.type == 'Identifier'){
                  vars[key.name] = null;
                }
                else return FAIL;
            }
            for(var i in bodies){
                if(walk(bodies[i]) === FAIL){
                    return FAIL;
                }
            }
            // restore the vars and scope after we walk
            vars = oldVars;
            
            var keys = Object.keys(vars);
            var vals = keys.map(function(key) {
                return vars[key];
            });
            return Function(keys.join(', '), 'return ' + unparse(node)).apply(null, vals);
        }
        else if (node.type === 'TemplateLiteral') {
            var str = '';
            for (var i = 0; i < node.expressions.length; i++) {
                str += walk(node.quasis[i]);
                str += walk(node.expressions[i]);
            }
            str += walk(node.quasis[i]);
            return str;
        }
        else if (node.type === 'TaggedTemplateExpression') {
            var tag = walk(node.tag);
            var quasi = node.quasi;
            var strings = quasi.quasis.map(walk);
            var values = quasi.expressions.map(walk);
            return tag.apply(null, [strings].concat(values));
        }
        else if (node.type === 'TemplateElement') {
            return node.value.cooked;
        }
        else return FAIL;
    })(ast);
    
    return result === FAIL ? undefined : result;
};

},{"escodegen":12}],"jsonpath":[function(require,module,exports){
module.exports = require('./lib/index');

},{"./lib/index":5}]},{},["jsonpath"])("jsonpath")
});


/***/ }),

/***/ 5641:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TabButton = void 0;
const React = __webpack_require__(6540);
const I18nLabel_1 = __webpack_require__(300);
const Actions_1 = __webpack_require__(9103);
const Rect_1 = __webpack_require__(2530);
const ICloseType_1 = __webpack_require__(5731);
const Types_1 = __webpack_require__(6643);
const Utils_1 = __webpack_require__(343);
/** @internal */
const TabButton = (props) => {
    const { layout, node, selected, iconFactory, titleFactory, icons, path } = props;
    const selfRef = React.useRef(null);
    const contentRef = React.useRef(null);
    const onMouseDown = (event) => {
        if (!(0, Utils_1.isAuxMouseEvent)(event) && !layout.getEditingTab()) {
            layout.dragStart(event, undefined, node, node.isEnableDrag(), onClick, onDoubleClick);
        }
    };
    const onAuxMouseClick = (event) => {
        if ((0, Utils_1.isAuxMouseEvent)(event)) {
            layout.auxMouseClick(node, event);
        }
    };
    const onContextMenu = (event) => {
        layout.showContextMenu(node, event);
    };
    const onClick = () => {
        layout.doAction(Actions_1.Actions.selectTab(node.getId()));
    };
    const onDoubleClick = (event) => {
        if (node.isEnableRename()) {
            onRename();
        }
    };
    const onRename = () => {
        layout.setEditingTab(node);
        layout.getCurrentDocument().body.addEventListener("mousedown", onEndEdit);
        layout.getCurrentDocument().body.addEventListener("touchstart", onEndEdit);
    };
    const onEndEdit = (event) => {
        if (event.target !== contentRef.current) {
            layout.getCurrentDocument().body.removeEventListener("mousedown", onEndEdit);
            layout.getCurrentDocument().body.removeEventListener("touchstart", onEndEdit);
            layout.setEditingTab(undefined);
        }
    };
    const isClosable = () => {
        const closeType = node.getCloseType();
        if (selected || closeType === ICloseType_1.ICloseType.Always) {
            return true;
        }
        if (closeType === ICloseType_1.ICloseType.Visible) {
            // not selected but x should be visible due to hover
            if (window.matchMedia && window.matchMedia("(hover: hover) and (pointer: fine)").matches) {
                return true;
            }
        }
        return false;
    };
    const onClose = (event) => {
        if (isClosable()) {
            layout.doAction(Actions_1.Actions.deleteTab(node.getId()));
        }
        else {
            onClick();
        }
    };
    const onCloseMouseDown = (event) => {
        event.stopPropagation();
    };
    React.useLayoutEffect(() => {
        updateRect();
        if (layout.getEditingTab() === node) {
            contentRef.current.select();
        }
    });
    const updateRect = () => {
        var _a;
        // record position of tab in node
        const layoutRect = layout.getDomRect();
        const r = (_a = selfRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
        if (r && layoutRect) {
            node._setTabRect(new Rect_1.Rect(r.left - layoutRect.left, r.top - layoutRect.top, r.width, r.height));
        }
    };
    const onTextBoxMouseDown = (event) => {
        // console.log("onTextBoxMouseDown");
        event.stopPropagation();
    };
    const onTextBoxKeyPress = (event) => {
        if (event.code === 'Escape') {
            // esc
            layout.setEditingTab(undefined);
        }
        else if (event.code === 'Enter') {
            // enter
            layout.setEditingTab(undefined);
            layout.doAction(Actions_1.Actions.renameTab(node.getId(), event.target.value));
        }
    };
    const cm = layout.getClassName;
    const parentNode = node.getParent();
    const isStretch = parentNode.isEnableSingleTabStretch() && parentNode.getChildren().length === 1;
    let baseClassName = isStretch ? Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_STRETCH : Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON;
    let classNames = cm(baseClassName);
    classNames += " " + cm(baseClassName + "_" + parentNode.getTabLocation());
    if (!isStretch) {
        if (selected) {
            classNames += " " + cm(baseClassName + "--selected");
        }
        else {
            classNames += " " + cm(baseClassName + "--unselected");
        }
    }
    if (node.getClassName() !== undefined) {
        classNames += " " + node.getClassName();
    }
    const renderState = (0, Utils_1.getRenderStateEx)(layout, node, iconFactory, titleFactory);
    let content = renderState.content ? (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_CONTENT) }, renderState.content)) : null;
    const leading = renderState.leading ? (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING) }, renderState.leading)) : null;
    if (layout.getEditingTab() === node) {
        content = (React.createElement("input", { ref: contentRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_TEXTBOX), "data-layout-path": path + "/textbox", type: "text", autoFocus: true, defaultValue: node.getName(), onKeyDown: onTextBoxKeyPress, onMouseDown: onTextBoxMouseDown, onTouchStart: onTextBoxMouseDown }));
    }
    if (node.isEnableClose() && !isStretch) {
        const closeTitle = layout.i18nName(I18nLabel_1.I18nLabel.Close_Tab);
        renderState.buttons.push(React.createElement("div", { key: "close", "data-layout-path": path + "/button/close", title: closeTitle, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_TRAILING), onMouseDown: onCloseMouseDown, onClick: onClose, onTouchStart: onCloseMouseDown }, (typeof icons.close === "function") ? icons.close(node) : icons.close));
    }
    return (React.createElement("div", { ref: selfRef, "data-layout-path": path, className: classNames, onMouseDown: onMouseDown, onClick: onAuxMouseClick, onAuxClick: onAuxMouseClick, onContextMenu: onContextMenu, onTouchStart: onMouseDown, title: node.getHelpText() },
        leading,
        content,
        renderState.buttons));
};
exports.TabButton = TabButton;
//# sourceMappingURL=TabButton.js.map

/***/ }),

/***/ 5655:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  A: function() { return /* binding */ createCache; }
});

;// ./node_modules/@emotion/sheet/dist/emotion-sheet.esm.js
var isDevelopment = false;

/*

Based off glamor's StyleSheet, thanks Sunil ❤️

high performance StyleSheet for css-in-js systems

- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance

// usage

import { StyleSheet } from '@emotion/sheet'

let styleSheet = new StyleSheet({ key: '', container: document.head })

styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet

styleSheet.flush()
- empties the stylesheet of all its contents

*/

function sheetForTag(tag) {
  if (tag.sheet) {
    return tag.sheet;
  } // this weirdness brought to you by firefox

  /* istanbul ignore next */


  for (var i = 0; i < document.styleSheets.length; i++) {
    if (document.styleSheets[i].ownerNode === tag) {
      return document.styleSheets[i];
    }
  } // this function should always return with a value
  // TS can't understand it though so we make it stop complaining here


  return undefined;
}

function createStyleElement(options) {
  var tag = document.createElement('style');
  tag.setAttribute('data-emotion', options.key);

  if (options.nonce !== undefined) {
    tag.setAttribute('nonce', options.nonce);
  }

  tag.appendChild(document.createTextNode(''));
  tag.setAttribute('data-s', '');
  return tag;
}

var StyleSheet = /*#__PURE__*/function () {
  // Using Node instead of HTMLElement since container may be a ShadowRoot
  function StyleSheet(options) {
    var _this = this;

    this._insertTag = function (tag) {
      var before;

      if (_this.tags.length === 0) {
        if (_this.insertionPoint) {
          before = _this.insertionPoint.nextSibling;
        } else if (_this.prepend) {
          before = _this.container.firstChild;
        } else {
          before = _this.before;
        }
      } else {
        before = _this.tags[_this.tags.length - 1].nextSibling;
      }

      _this.container.insertBefore(tag, before);

      _this.tags.push(tag);
    };

    this.isSpeedy = options.speedy === undefined ? !isDevelopment : options.speedy;
    this.tags = [];
    this.ctr = 0;
    this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets

    this.key = options.key;
    this.container = options.container;
    this.prepend = options.prepend;
    this.insertionPoint = options.insertionPoint;
    this.before = null;
  }

  var _proto = StyleSheet.prototype;

  _proto.hydrate = function hydrate(nodes) {
    nodes.forEach(this._insertTag);
  };

  _proto.insert = function insert(rule) {
    // the max length is how many rules we have per style tag, it's 65000 in speedy mode
    // it's 1 in dev because we insert source maps that map a single rule to a location
    // and you can only have one source map per style tag
    if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
      this._insertTag(createStyleElement(this));
    }

    var tag = this.tags[this.tags.length - 1];

    if (this.isSpeedy) {
      var sheet = sheetForTag(tag);

      try {
        // this is the ultrafast version, works across browsers
        // the big drawback is that the css won't be editable in devtools
        sheet.insertRule(rule, sheet.cssRules.length);
      } catch (e) {
      }
    } else {
      tag.appendChild(document.createTextNode(rule));
    }

    this.ctr++;
  };

  _proto.flush = function flush() {
    this.tags.forEach(function (tag) {
      var _tag$parentNode;

      return (_tag$parentNode = tag.parentNode) == null ? void 0 : _tag$parentNode.removeChild(tag);
    });
    this.tags = [];
    this.ctr = 0;
  };

  return StyleSheet;
}();



;// ./node_modules/stylis/src/Utility.js
/**
 * @param {number}
 * @return {number}
 */
var abs = Math.abs

/**
 * @param {number}
 * @return {string}
 */
var Utility_from = String.fromCharCode

/**
 * @param {object}
 * @return {object}
 */
var Utility_assign = Object.assign

/**
 * @param {string} value
 * @param {number} length
 * @return {number}
 */
function hash (value, length) {
	return Utility_charat(value, 0) ^ 45 ? (((((((length << 2) ^ Utility_charat(value, 0)) << 2) ^ Utility_charat(value, 1)) << 2) ^ Utility_charat(value, 2)) << 2) ^ Utility_charat(value, 3) : 0
}

/**
 * @param {string} value
 * @return {string}
 */
function trim (value) {
	return value.trim()
}

/**
 * @param {string} value
 * @param {RegExp} pattern
 * @return {string?}
 */
function Utility_match (value, pattern) {
	return (value = pattern.exec(value)) ? value[0] : value
}

/**
 * @param {string} value
 * @param {(string|RegExp)} pattern
 * @param {string} replacement
 * @return {string}
 */
function Utility_replace (value, pattern, replacement) {
	return value.replace(pattern, replacement)
}

/**
 * @param {string} value
 * @param {string} search
 * @return {number}
 */
function indexof (value, search) {
	return value.indexOf(search)
}

/**
 * @param {string} value
 * @param {number} index
 * @return {number}
 */
function Utility_charat (value, index) {
	return value.charCodeAt(index) | 0
}

/**
 * @param {string} value
 * @param {number} begin
 * @param {number} end
 * @return {string}
 */
function Utility_substr (value, begin, end) {
	return value.slice(begin, end)
}

/**
 * @param {string} value
 * @return {number}
 */
function Utility_strlen (value) {
	return value.length
}

/**
 * @param {any[]} value
 * @return {number}
 */
function Utility_sizeof (value) {
	return value.length
}

/**
 * @param {any} value
 * @param {any[]} array
 * @return {any}
 */
function Utility_append (value, array) {
	return array.push(value), value
}

/**
 * @param {string[]} array
 * @param {function} callback
 * @return {string}
 */
function Utility_combine (array, callback) {
	return array.map(callback).join('')
}

;// ./node_modules/stylis/src/Tokenizer.js


var line = 1
var column = 1
var Tokenizer_length = 0
var position = 0
var character = 0
var characters = ''

/**
 * @param {string} value
 * @param {object | null} root
 * @param {object | null} parent
 * @param {string} type
 * @param {string[] | string} props
 * @param {object[] | string} children
 * @param {number} length
 */
function node (value, root, parent, type, props, children, length) {
	return {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''}
}

/**
 * @param {object} root
 * @param {object} props
 * @return {object}
 */
function Tokenizer_copy (root, props) {
	return Utility_assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)
}

/**
 * @return {number}
 */
function Tokenizer_char () {
	return character
}

/**
 * @return {number}
 */
function prev () {
	character = position > 0 ? Utility_charat(characters, --position) : 0

	if (column--, character === 10)
		column = 1, line--

	return character
}

/**
 * @return {number}
 */
function next () {
	character = position < Tokenizer_length ? Utility_charat(characters, position++) : 0

	if (column++, character === 10)
		column = 1, line++

	return character
}

/**
 * @return {number}
 */
function peek () {
	return Utility_charat(characters, position)
}

/**
 * @return {number}
 */
function caret () {
	return position
}

/**
 * @param {number} begin
 * @param {number} end
 * @return {string}
 */
function slice (begin, end) {
	return Utility_substr(characters, begin, end)
}

/**
 * @param {number} type
 * @return {number}
 */
function token (type) {
	switch (type) {
		// \0 \t \n \r \s whitespace token
		case 0: case 9: case 10: case 13: case 32:
			return 5
		// ! + , / > @ ~ isolate token
		case 33: case 43: case 44: case 47: case 62: case 64: case 126:
		// ; { } breakpoint token
		case 59: case 123: case 125:
			return 4
		// : accompanied token
		case 58:
			return 3
		// " ' ( [ opening delimit token
		case 34: case 39: case 40: case 91:
			return 2
		// ) ] closing delimit token
		case 41: case 93:
			return 1
	}

	return 0
}

/**
 * @param {string} value
 * @return {any[]}
 */
function alloc (value) {
	return line = column = 1, Tokenizer_length = Utility_strlen(characters = value), position = 0, []
}

/**
 * @param {any} value
 * @return {any}
 */
function dealloc (value) {
	return characters = '', value
}

/**
 * @param {number} type
 * @return {string}
 */
function delimit (type) {
	return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))
}

/**
 * @param {string} value
 * @return {string[]}
 */
function Tokenizer_tokenize (value) {
	return dealloc(tokenizer(alloc(value)))
}

/**
 * @param {number} type
 * @return {string}
 */
function whitespace (type) {
	while (character = peek())
		if (character < 33)
			next()
		else
			break

	return token(type) > 2 || token(character) > 3 ? '' : ' '
}

/**
 * @param {string[]} children
 * @return {string[]}
 */
function tokenizer (children) {
	while (next())
		switch (token(character)) {
			case 0: append(identifier(position - 1), children)
				break
			case 2: append(delimit(character), children)
				break
			default: append(from(character), children)
		}

	return children
}

/**
 * @param {number} index
 * @param {number} count
 * @return {string}
 */
function escaping (index, count) {
	while (--count && next())
		// not 0-9 A-F a-f
		if (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))
			break

	return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))
}

/**
 * @param {number} type
 * @return {number}
 */
function delimiter (type) {
	while (next())
		switch (character) {
			// ] ) " '
			case type:
				return position
			// " '
			case 34: case 39:
				if (type !== 34 && type !== 39)
					delimiter(character)
				break
			// (
			case 40:
				if (type === 41)
					delimiter(type)
				break
			// \
			case 92:
				next()
				break
		}

	return position
}

/**
 * @param {number} type
 * @param {number} index
 * @return {number}
 */
function commenter (type, index) {
	while (next())
		// //
		if (type + character === 47 + 10)
			break
		// /*
		else if (type + character === 42 + 42 && peek() === 47)
			break

	return '/*' + slice(index, position - 1) + '*' + Utility_from(type === 47 ? type : next())
}

/**
 * @param {number} index
 * @return {string}
 */
function identifier (index) {
	while (!token(peek()))
		next()

	return slice(index, position)
}

;// ./node_modules/stylis/src/Enum.js
var Enum_MS = '-ms-'
var Enum_MOZ = '-moz-'
var Enum_WEBKIT = '-webkit-'

var COMMENT = 'comm'
var Enum_RULESET = 'rule'
var Enum_DECLARATION = 'decl'

var PAGE = '@page'
var MEDIA = '@media'
var IMPORT = '@import'
var CHARSET = '@charset'
var VIEWPORT = '@viewport'
var SUPPORTS = '@supports'
var DOCUMENT = '@document'
var NAMESPACE = '@namespace'
var Enum_KEYFRAMES = '@keyframes'
var FONT_FACE = '@font-face'
var COUNTER_STYLE = '@counter-style'
var FONT_FEATURE_VALUES = '@font-feature-values'
var LAYER = '@layer'

;// ./node_modules/stylis/src/Serializer.js



/**
 * @param {object[]} children
 * @param {function} callback
 * @return {string}
 */
function Serializer_serialize (children, callback) {
	var output = ''
	var length = Utility_sizeof(children)

	for (var i = 0; i < length; i++)
		output += callback(children[i], i, children, callback) || ''

	return output
}

/**
 * @param {object} element
 * @param {number} index
 * @param {object[]} children
 * @param {function} callback
 * @return {string}
 */
function stringify (element, index, children, callback) {
	switch (element.type) {
		case LAYER: if (element.children.length) break
		case IMPORT: case Enum_DECLARATION: return element.return = element.return || element.value
		case COMMENT: return ''
		case Enum_KEYFRAMES: return element.return = element.value + '{' + Serializer_serialize(element.children, callback) + '}'
		case Enum_RULESET: element.value = element.props.join(',')
	}

	return Utility_strlen(children = Serializer_serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''
}

;// ./node_modules/stylis/src/Middleware.js






/**
 * @param {function[]} collection
 * @return {function}
 */
function middleware (collection) {
	var length = Utility_sizeof(collection)

	return function (element, index, children, callback) {
		var output = ''

		for (var i = 0; i < length; i++)
			output += collection[i](element, index, children, callback) || ''

		return output
	}
}

/**
 * @param {function} callback
 * @return {function}
 */
function rulesheet (callback) {
	return function (element) {
		if (!element.root)
			if (element = element.return)
				callback(element)
	}
}

/**
 * @param {object} element
 * @param {number} index
 * @param {object[]} children
 * @param {function} callback
 */
function prefixer (element, index, children, callback) {
	if (element.length > -1)
		if (!element.return)
			switch (element.type) {
				case DECLARATION: element.return = prefix(element.value, element.length, children)
					return
				case KEYFRAMES:
					return serialize([copy(element, {value: replace(element.value, '@', '@' + WEBKIT)})], callback)
				case RULESET:
					if (element.length)
						return combine(element.props, function (value) {
							switch (match(value, /(::plac\w+|:read-\w+)/)) {
								// :read-(only|write)
								case ':read-only': case ':read-write':
									return serialize([copy(element, {props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]})], callback)
								// :placeholder
								case '::placeholder':
									return serialize([
										copy(element, {props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]}),
										copy(element, {props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]}),
										copy(element, {props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]})
									], callback)
							}

							return ''
						})
			}
}

/**
 * @param {object} element
 * @param {number} index
 * @param {object[]} children
 */
function namespace (element) {
	switch (element.type) {
		case RULESET:
			element.props = element.props.map(function (value) {
				return combine(tokenize(value), function (value, index, children) {
					switch (charat(value, 0)) {
						// \f
						case 12:
							return substr(value, 1, strlen(value))
						// \0 ( + > ~
						case 0: case 40: case 43: case 62: case 126:
							return value
						// :
						case 58:
							if (children[++index] === 'global')
								children[index] = '', children[++index] = '\f' + substr(children[index], index = 1, -1)
						// \s
						case 32:
							return index === 1 ? '' : value
						default:
							switch (index) {
								case 0: element = value
									return sizeof(children) > 1 ? '' : value
								case index = sizeof(children) - 1: case 2:
									return index === 2 ? value + element + element : value + element
								default:
									return value
							}
					}
				})
			})
	}
}

;// ./node_modules/stylis/src/Parser.js




/**
 * @param {string} value
 * @return {object[]}
 */
function compile (value) {
	return dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value))
}

/**
 * @param {string} value
 * @param {object} root
 * @param {object?} parent
 * @param {string[]} rule
 * @param {string[]} rules
 * @param {string[]} rulesets
 * @param {number[]} pseudo
 * @param {number[]} points
 * @param {string[]} declarations
 * @return {object}
 */
function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
	var index = 0
	var offset = 0
	var length = pseudo
	var atrule = 0
	var property = 0
	var previous = 0
	var variable = 1
	var scanning = 1
	var ampersand = 1
	var character = 0
	var type = ''
	var props = rules
	var children = rulesets
	var reference = rule
	var characters = type

	while (scanning)
		switch (previous = character, character = next()) {
			// (
			case 40:
				if (previous != 108 && Utility_charat(characters, length - 1) == 58) {
					if (indexof(characters += Utility_replace(delimit(character), '&', '&\f'), '&\f') != -1)
						ampersand = -1
					break
				}
			// " ' [
			case 34: case 39: case 91:
				characters += delimit(character)
				break
			// \t \n \r \s
			case 9: case 10: case 13: case 32:
				characters += whitespace(previous)
				break
			// \
			case 92:
				characters += escaping(caret() - 1, 7)
				continue
			// /
			case 47:
				switch (peek()) {
					case 42: case 47:
						Utility_append(comment(commenter(next(), caret()), root, parent), declarations)
						break
					default:
						characters += '/'
				}
				break
			// {
			case 123 * variable:
				points[index++] = Utility_strlen(characters) * ampersand
			// } ; \0
			case 125 * variable: case 59: case 0:
				switch (character) {
					// \0 }
					case 0: case 125: scanning = 0
					// ;
					case 59 + offset: if (ampersand == -1) characters = Utility_replace(characters, /\f/g, '')
						if (property > 0 && (Utility_strlen(characters) - length))
							Utility_append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(Utility_replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations)
						break
					// @ ;
					case 59: characters += ';'
					// { rule/at-rule
					default:
						Utility_append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets)

						if (character === 123)
							if (offset === 0)
								parse(characters, root, reference, reference, props, rulesets, length, points, children)
							else
								switch (atrule === 99 && Utility_charat(characters, 3) === 110 ? 100 : atrule) {
									// d l m s
									case 100: case 108: case 109: case 115:
										parse(value, reference, reference, rule && Utility_append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children)
										break
									default:
										parse(characters, reference, reference, reference, [''], children, 0, points, children)
								}
				}

				index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo
				break
			// :
			case 58:
				length = 1 + Utility_strlen(characters), property = previous
			default:
				if (variable < 1)
					if (character == 123)
						--variable
					else if (character == 125 && variable++ == 0 && prev() == 125)
						continue

				switch (characters += Utility_from(character), character * variable) {
					// &
					case 38:
						ampersand = offset > 0 ? 1 : (characters += '\f', -1)
						break
					// ,
					case 44:
						points[index++] = (Utility_strlen(characters) - 1) * ampersand, ampersand = 1
						break
					// @
					case 64:
						// -
						if (peek() === 45)
							characters += delimit(next())

						atrule = peek(), offset = length = Utility_strlen(type = characters += identifier(caret())), character++
						break
					// -
					case 45:
						if (previous === 45 && Utility_strlen(characters) == 2)
							variable = 0
				}
		}

	return rulesets
}

/**
 * @param {string} value
 * @param {object} root
 * @param {object?} parent
 * @param {number} index
 * @param {number} offset
 * @param {string[]} rules
 * @param {number[]} points
 * @param {string} type
 * @param {string[]} props
 * @param {string[]} children
 * @param {number} length
 * @return {object}
 */
function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) {
	var post = offset - 1
	var rule = offset === 0 ? rules : ['']
	var size = Utility_sizeof(rule)

	for (var i = 0, j = 0, k = 0; i < index; ++i)
		for (var x = 0, y = Utility_substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)
			if (z = trim(j > 0 ? rule[x] + ' ' + y : Utility_replace(y, /&\f/g, rule[x])))
				props[k++] = z

	return node(value, root, parent, offset === 0 ? Enum_RULESET : type, props, children, length)
}

/**
 * @param {number} value
 * @param {object} root
 * @param {object?} parent
 * @return {object}
 */
function comment (value, root, parent) {
	return node(value, root, parent, COMMENT, Utility_from(Tokenizer_char()), Utility_substr(value, 2, -2), 0)
}

/**
 * @param {string} value
 * @param {object} root
 * @param {object?} parent
 * @param {number} length
 * @return {object}
 */
function declaration (value, root, parent, length) {
	return node(value, root, parent, Enum_DECLARATION, Utility_substr(value, 0, length), Utility_substr(value, length + 1, -1), length)
}

;// ./node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js





var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
  var previous = 0;
  var character = 0;

  while (true) {
    previous = character;
    character = peek(); // &\f

    if (previous === 38 && character === 12) {
      points[index] = 1;
    }

    if (token(character)) {
      break;
    }

    next();
  }

  return slice(begin, position);
};

var toRules = function toRules(parsed, points) {
  // pretend we've started with a comma
  var index = -1;
  var character = 44;

  do {
    switch (token(character)) {
      case 0:
        // &\f
        if (character === 38 && peek() === 12) {
          // this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
          // stylis inserts \f after & to know when & where it should replace this sequence with the context selector
          // and when it should just concatenate the outer and inner selectors
          // it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
          points[index] = 1;
        }

        parsed[index] += identifierWithPointTracking(position - 1, points, index);
        break;

      case 2:
        parsed[index] += delimit(character);
        break;

      case 4:
        // comma
        if (character === 44) {
          // colon
          parsed[++index] = peek() === 58 ? '&\f' : '';
          points[index] = parsed[index].length;
          break;
        }

      // fallthrough

      default:
        parsed[index] += Utility_from(character);
    }
  } while (character = next());

  return parsed;
};

var getRules = function getRules(value, points) {
  return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11


var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
  if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
  // negative .length indicates that this rule has been already prefixed
  element.length < 1) {
    return;
  }

  var value = element.value;
  var parent = element.parent;
  var isImplicitRule = element.column === parent.column && element.line === parent.line;

  while (parent.type !== 'rule') {
    parent = parent.parent;
    if (!parent) return;
  } // short-circuit for the simplest case


  if (element.props.length === 1 && value.charCodeAt(0) !== 58
  /* colon */
  && !fixedElements.get(parent)) {
    return;
  } // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
  // then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"


  if (isImplicitRule) {
    return;
  }

  fixedElements.set(element, true);
  var points = [];
  var rules = getRules(value, points);
  var parentRules = parent.props;

  for (var i = 0, k = 0; i < rules.length; i++) {
    for (var j = 0; j < parentRules.length; j++, k++) {
      element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
    }
  }
};
var removeLabel = function removeLabel(element) {
  if (element.type === 'decl') {
    var value = element.value;

    if ( // charcode for l
    value.charCodeAt(0) === 108 && // charcode for b
    value.charCodeAt(2) === 98) {
      // this ignores label
      element["return"] = '';
      element.value = '';
    }
  }
};

/* eslint-disable no-fallthrough */

function emotion_cache_browser_esm_prefix(value, length) {
  switch (hash(value, length)) {
    // color-adjust
    case 5103:
      return Enum_WEBKIT + 'print-' + value + value;
    // animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)

    case 5737:
    case 4201:
    case 3177:
    case 3433:
    case 1641:
    case 4457:
    case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break

    case 5572:
    case 6356:
    case 5844:
    case 3191:
    case 6645:
    case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,

    case 6391:
    case 5879:
    case 5623:
    case 6135:
    case 4599:
    case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)

    case 4215:
    case 6389:
    case 5109:
    case 5365:
    case 5621:
    case 3829:
      return Enum_WEBKIT + value + value;
    // appearance, user-select, transform, hyphens, text-size-adjust

    case 5349:
    case 4246:
    case 4810:
    case 6968:
    case 2756:
      return Enum_WEBKIT + value + Enum_MOZ + value + Enum_MS + value + value;
    // flex, flex-direction

    case 6828:
    case 4268:
      return Enum_WEBKIT + value + Enum_MS + value + value;
    // order

    case 6165:
      return Enum_WEBKIT + value + Enum_MS + 'flex-' + value + value;
    // align-items

    case 5187:
      return Enum_WEBKIT + value + Utility_replace(value, /(\w+).+(:[^]+)/, Enum_WEBKIT + 'box-$1$2' + Enum_MS + 'flex-$1$2') + value;
    // align-self

    case 5443:
      return Enum_WEBKIT + value + Enum_MS + 'flex-item-' + Utility_replace(value, /flex-|-self/, '') + value;
    // align-content

    case 4675:
      return Enum_WEBKIT + value + Enum_MS + 'flex-line-pack' + Utility_replace(value, /align-content|flex-|-self/, '') + value;
    // flex-shrink

    case 5548:
      return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'shrink', 'negative') + value;
    // flex-basis

    case 5292:
      return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'basis', 'preferred-size') + value;
    // flex-grow

    case 6060:
      return Enum_WEBKIT + 'box-' + Utility_replace(value, '-grow', '') + Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'grow', 'positive') + value;
    // transition

    case 4554:
      return Enum_WEBKIT + Utility_replace(value, /([^-])(transform)/g, '$1' + Enum_WEBKIT + '$2') + value;
    // cursor

    case 6187:
      return Utility_replace(Utility_replace(Utility_replace(value, /(zoom-|grab)/, Enum_WEBKIT + '$1'), /(image-set)/, Enum_WEBKIT + '$1'), value, '') + value;
    // background, background-image

    case 5495:
    case 3959:
      return Utility_replace(value, /(image-set\([^]*)/, Enum_WEBKIT + '$1' + '$`$1');
    // justify-content

    case 4968:
      return Utility_replace(Utility_replace(value, /(.+:)(flex-)?(.*)/, Enum_WEBKIT + 'box-pack:$3' + Enum_MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + Enum_WEBKIT + value + value;
    // (margin|padding)-inline-(start|end)

    case 4095:
    case 3583:
    case 4068:
    case 2532:
      return Utility_replace(value, /(.+)-inline(.+)/, Enum_WEBKIT + '$1$2') + value;
    // (min|max)?(width|height|inline-size|block-size)

    case 8116:
    case 7059:
    case 5753:
    case 5535:
    case 5445:
    case 5701:
    case 4933:
    case 4677:
    case 5533:
    case 5789:
    case 5021:
    case 4765:
      // stretch, max-content, min-content, fill-available
      if (Utility_strlen(value) - 1 - length > 6) switch (Utility_charat(value, length + 1)) {
        // (m)ax-content, (m)in-content
        case 109:
          // -
          if (Utility_charat(value, length + 4) !== 45) break;
        // (f)ill-available, (f)it-content

        case 102:
          return Utility_replace(value, /(.+:)(.+)-([^]+)/, '$1' + Enum_WEBKIT + '$2-$3' + '$1' + Enum_MOZ + (Utility_charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
        // (s)tretch

        case 115:
          return ~indexof(value, 'stretch') ? emotion_cache_browser_esm_prefix(Utility_replace(value, 'stretch', 'fill-available'), length) + value : value;
      }
      break;
    // position: sticky

    case 4949:
      // (s)ticky?
      if (Utility_charat(value, length + 1) !== 115) break;
    // display: (flex|inline-flex)

    case 6444:
      switch (Utility_charat(value, Utility_strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
        // stic(k)y
        case 107:
          return Utility_replace(value, ':', ':' + Enum_WEBKIT) + value;
        // (inline-)?fl(e)x

        case 101:
          return Utility_replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + Enum_WEBKIT + (Utility_charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + Enum_WEBKIT + '$2$3' + '$1' + Enum_MS + '$2box$3') + value;
      }

      break;
    // writing-mode

    case 5936:
      switch (Utility_charat(value, length + 11)) {
        // vertical-l(r)
        case 114:
          return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
        // vertical-r(l)

        case 108:
          return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
        // horizontal(-)tb

        case 45:
          return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
      }

      return Enum_WEBKIT + value + Enum_MS + value + value;
  }

  return value;
}

var emotion_cache_browser_esm_prefixer = function prefixer(element, index, children, callback) {
  if (element.length > -1) if (!element["return"]) switch (element.type) {
    case Enum_DECLARATION:
      element["return"] = emotion_cache_browser_esm_prefix(element.value, element.length);
      break;

    case Enum_KEYFRAMES:
      return Serializer_serialize([Tokenizer_copy(element, {
        value: Utility_replace(element.value, '@', '@' + Enum_WEBKIT)
      })], callback);

    case Enum_RULESET:
      if (element.length) return Utility_combine(element.props, function (value) {
        switch (Utility_match(value, /(::plac\w+|:read-\w+)/)) {
          // :read-(only|write)
          case ':read-only':
          case ':read-write':
            return Serializer_serialize([Tokenizer_copy(element, {
              props: [Utility_replace(value, /:(read-\w+)/, ':' + Enum_MOZ + '$1')]
            })], callback);
          // :placeholder

          case '::placeholder':
            return Serializer_serialize([Tokenizer_copy(element, {
              props: [Utility_replace(value, /:(plac\w+)/, ':' + Enum_WEBKIT + 'input-$1')]
            }), Tokenizer_copy(element, {
              props: [Utility_replace(value, /:(plac\w+)/, ':' + Enum_MOZ + '$1')]
            }), Tokenizer_copy(element, {
              props: [Utility_replace(value, /:(plac\w+)/, Enum_MS + 'input-$1')]
            })], callback);
        }

        return '';
      });
  }
};

var defaultStylisPlugins = [emotion_cache_browser_esm_prefixer];

var createCache = function createCache(options) {
  var key = options.key;

  if (key === 'css') {
    var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
    // document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
    // note this very very intentionally targets all style elements regardless of the key to ensure
    // that creating a cache works inside of render of a React component

    Array.prototype.forEach.call(ssrStyles, function (node) {
      // we want to only move elements which have a space in the data-emotion attribute value
      // because that indicates that it is an Emotion 11 server-side rendered style elements
      // while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
      // Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
      // so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
      // will not result in the Emotion 10 styles being destroyed
      var dataEmotionAttribute = node.getAttribute('data-emotion');

      if (dataEmotionAttribute.indexOf(' ') === -1) {
        return;
      }

      document.head.appendChild(node);
      node.setAttribute('data-s', '');
    });
  }

  var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;

  var inserted = {};
  var container;
  var nodesToHydrate = [];

  {
    container = options.container || document.head;
    Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
    // means that the style elements we're looking at are only Emotion 11 server-rendered style elements
    document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
      var attrib = node.getAttribute("data-emotion").split(' ');

      for (var i = 1; i < attrib.length; i++) {
        inserted[attrib[i]] = true;
      }

      nodesToHydrate.push(node);
    });
  }

  var _insert;

  var omnipresentPlugins = [compat, removeLabel];

  {
    var currentSheet;
    var finalizingPlugins = [stringify, rulesheet(function (rule) {
      currentSheet.insert(rule);
    })];
    var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));

    var stylis = function stylis(styles) {
      return Serializer_serialize(compile(styles), serializer);
    };

    _insert = function insert(selector, serialized, sheet, shouldCache) {
      currentSheet = sheet;

      stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);

      if (shouldCache) {
        cache.inserted[serialized.name] = true;
      }
    };
  }

  var cache = {
    key: key,
    sheet: new StyleSheet({
      key: key,
      container: container,
      nonce: options.nonce,
      speedy: options.speedy,
      prepend: options.prepend,
      insertionPoint: options.insertionPoint
    }),
    nonce: options.nonce,
    inserted: inserted,
    registered: {},
    insert: _insert
  };
  cache.sheet.hydrate(nodesToHydrate);
  return cache;
};




/***/ }),

/***/ 5731:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ICloseType = void 0;
var ICloseType;
(function (ICloseType) {
    ICloseType[ICloseType["Visible"] = 1] = "Visible";
    ICloseType[ICloseType["Always"] = 2] = "Always";
    ICloseType[ICloseType["Selected"] = 3] = "Selected";
})(ICloseType = exports.ICloseType || (exports.ICloseType = {}));
//# sourceMappingURL=ICloseType.js.map

/***/ }),

/***/ 5742:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BorderButton = void 0;
const React = __webpack_require__(6540);
const I18nLabel_1 = __webpack_require__(300);
const Actions_1 = __webpack_require__(9103);
const Rect_1 = __webpack_require__(2530);
const ICloseType_1 = __webpack_require__(5731);
const Types_1 = __webpack_require__(6643);
const Utils_1 = __webpack_require__(343);
/** @internal */
const BorderButton = (props) => {
    const { layout, node, selected, border, iconFactory, titleFactory, icons, path } = props;
    const selfRef = React.useRef(null);
    const contentRef = React.useRef(null);
    const onMouseDown = (event) => {
        if (!(0, Utils_1.isAuxMouseEvent)(event) && !layout.getEditingTab()) {
            layout.dragStart(event, undefined, node, node.isEnableDrag(), onClick, onDoubleClick);
        }
    };
    const onAuxMouseClick = (event) => {
        if ((0, Utils_1.isAuxMouseEvent)(event)) {
            layout.auxMouseClick(node, event);
        }
    };
    const onContextMenu = (event) => {
        layout.showContextMenu(node, event);
    };
    const onClick = () => {
        layout.doAction(Actions_1.Actions.selectTab(node.getId()));
    };
    const onDoubleClick = (event) => {
        // if (node.isEnableRename()) {
        //     onRename();
        // }
    };
    // const onRename = () => {
    //     layout.setEditingTab(node);
    //     layout.getCurrentDocument()!.body.addEventListener("mousedown", onEndEdit);
    //     layout.getCurrentDocument()!.body.addEventListener("touchstart", onEndEdit);
    // };
    const onEndEdit = (event) => {
        if (event.target !== contentRef.current) {
            layout.getCurrentDocument().body.removeEventListener("mousedown", onEndEdit);
            layout.getCurrentDocument().body.removeEventListener("touchstart", onEndEdit);
            layout.setEditingTab(undefined);
        }
    };
    const isClosable = () => {
        const closeType = node.getCloseType();
        if (selected || closeType === ICloseType_1.ICloseType.Always) {
            return true;
        }
        if (closeType === ICloseType_1.ICloseType.Visible) {
            // not selected but x should be visible due to hover
            if (window.matchMedia && window.matchMedia("(hover: hover) and (pointer: fine)").matches) {
                return true;
            }
        }
        return false;
    };
    const onClose = (event) => {
        if (isClosable()) {
            layout.doAction(Actions_1.Actions.deleteTab(node.getId()));
        }
        else {
            onClick();
        }
    };
    const onCloseMouseDown = (event) => {
        event.stopPropagation();
    };
    React.useLayoutEffect(() => {
        updateRect();
        if (layout.getEditingTab() === node) {
            contentRef.current.select();
        }
    });
    const updateRect = () => {
        var _a;
        // record position of tab in node
        const layoutRect = layout.getDomRect();
        const r = (_a = selfRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
        if (r && layoutRect) {
            node._setTabRect(new Rect_1.Rect(r.left - layoutRect.left, r.top - layoutRect.top, r.width, r.height));
        }
    };
    const onTextBoxMouseDown = (event) => {
        // console.log("onTextBoxMouseDown");
        event.stopPropagation();
    };
    const onTextBoxKeyPress = (event) => {
        if (event.code === 'Escape') {
            // esc
            layout.setEditingTab(undefined);
        }
        else if (event.code === 'Enter') {
            // enter
            layout.setEditingTab(undefined);
            layout.doAction(Actions_1.Actions.renameTab(node.getId(), event.target.value));
        }
    };
    const cm = layout.getClassName;
    let classNames = cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON) + " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON_ + border);
    if (selected) {
        classNames += " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON__SELECTED);
    }
    else {
        classNames += " " + cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON__UNSELECTED);
    }
    if (node.getClassName() !== undefined) {
        classNames += " " + node.getClassName();
    }
    let iconAngle = 0;
    if (node.getModel().isEnableRotateBorderIcons() === false) {
        if (border === "left") {
            iconAngle = 90;
        }
        else if (border === "right") {
            iconAngle = -90;
        }
    }
    const renderState = (0, Utils_1.getRenderStateEx)(layout, node, iconFactory, titleFactory, iconAngle);
    let content = renderState.content ? (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON_CONTENT) }, renderState.content)) : null;
    const leading = renderState.leading ? (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON_LEADING) }, renderState.leading)) : null;
    if (layout.getEditingTab() === node) {
        content = (React.createElement("input", { ref: contentRef, className: cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BUTTON_TEXTBOX), "data-layout-path": path + "/textbox", type: "text", autoFocus: true, defaultValue: node.getName(), onKeyDown: onTextBoxKeyPress, onMouseDown: onTextBoxMouseDown, onTouchStart: onTextBoxMouseDown }));
    }
    if (node.isEnableClose()) {
        const closeTitle = layout.i18nName(I18nLabel_1.I18nLabel.Close_Tab);
        renderState.buttons.push(React.createElement("div", { key: "close", "data-layout-path": path + "/button/close", title: closeTitle, className: cm(Types_1.CLASSES.FLEXLAYOUT__BORDER_BUTTON_TRAILING), onMouseDown: onCloseMouseDown, onClick: onClose, onTouchStart: onCloseMouseDown }, (typeof icons.close === "function") ? icons.close(node) : icons.close));
    }
    return (React.createElement("div", { ref: selfRef, "data-layout-path": path, className: classNames, onMouseDown: onMouseDown, onClick: onAuxMouseClick, onAuxClick: onAuxMouseClick, onContextMenu: onContextMenu, onTouchStart: onMouseDown, title: node.getHelpText() },
        leading,
        content,
        renderState.buttons));
};
exports.BorderButton = BorderButton;
//# sourceMappingURL=BorderButton.js.map

/***/ }),

/***/ 6169:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SplitterNode = void 0;
const AttributeDefinitions_1 = __webpack_require__(6874);
const Orientation_1 = __webpack_require__(1648);
const Node_1 = __webpack_require__(7618);
class SplitterNode extends Node_1.Node {
    /** @internal */
    constructor(model) {
        super(model);
        this._fixed = true;
        this._attributes.type = SplitterNode.TYPE;
        model._addNode(this);
    }
    /** @internal */
    getWidth() {
        return this._model.getSplitterSize();
    }
    /** @internal */
    getMinWidth() {
        if (this.getOrientation() === Orientation_1.Orientation.VERT) {
            return this._model.getSplitterSize();
        }
        else {
            return 0;
        }
    }
    /** @internal */
    getHeight() {
        return this._model.getSplitterSize();
    }
    /** @internal */
    getMinHeight() {
        if (this.getOrientation() === Orientation_1.Orientation.HORZ) {
            return this._model.getSplitterSize();
        }
        else {
            return 0;
        }
    }
    /** @internal */
    getMinSize(orientation) {
        if (orientation === Orientation_1.Orientation.HORZ) {
            return this.getMinWidth();
        }
        else {
            return this.getMinHeight();
        }
    }
    /** @internal */
    getWeight() {
        return 0;
    }
    /** @internal */
    _setWeight(value) { }
    /** @internal */
    _getPrefSize(orientation) {
        return this._model.getSplitterSize();
    }
    /** @internal */
    _updateAttrs(json) { }
    /** @internal */
    _getAttributeDefinitions() {
        return new AttributeDefinitions_1.AttributeDefinitions();
    }
    toJson() {
        return undefined;
    }
}
exports.SplitterNode = SplitterNode;
SplitterNode.TYPE = "splitter";
//# sourceMappingURL=SplitterNode.js.map

/***/ }),

/***/ 6289:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: function() { return /* binding */ memoize; }
/* harmony export */ });
function memoize(fn) {
  var cache = Object.create(null);
  return function (arg) {
    if (cache[arg] === undefined) cache[arg] = fn(arg);
    return cache[arg];
  };
}




/***/ }),

/***/ 6426:
/***/ (function(module) {


module.exports = function () {
  var selection = document.getSelection();
  if (!selection.rangeCount) {
    return function () {};
  }
  var active = document.activeElement;

  var ranges = [];
  for (var i = 0; i < selection.rangeCount; i++) {
    ranges.push(selection.getRangeAt(i));
  }

  switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML
    case 'INPUT':
    case 'TEXTAREA':
      active.blur();
      break;

    default:
      active = null;
      break;
  }

  selection.removeAllRanges();
  return function () {
    selection.type === 'Caret' &&
    selection.removeAllRanges();

    if (!selection.rangeCount) {
      ranges.forEach(function(range) {
        selection.addRange(range);
      });
    }

    active &&
    active.focus();
  };
};


/***/ }),

/***/ 6643:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CLASSES = void 0;
var CLASSES;
(function (CLASSES) {
    CLASSES["FLEXLAYOUT__BORDER"] = "flexlayout__border";
    CLASSES["FLEXLAYOUT__BORDER_"] = "flexlayout__border_";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON"] = "flexlayout__border_button";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON_"] = "flexlayout__border_button_";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON_CONTENT"] = "flexlayout__border_button_content";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON_LEADING"] = "flexlayout__border_button_leading";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON_TRAILING"] = "flexlayout__border_button_trailing";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON__SELECTED"] = "flexlayout__border_button--selected";
    CLASSES["FLEXLAYOUT__BORDER_BUTTON__UNSELECTED"] = "flexlayout__border_button--unselected";
    CLASSES["FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW"] = "flexlayout__border_toolbar_button_overflow";
    CLASSES["FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW_"] = "flexlayout__border_toolbar_button_overflow_";
    CLASSES["FLEXLAYOUT__BORDER_INNER"] = "flexlayout__border_inner";
    CLASSES["FLEXLAYOUT__BORDER_INNER_"] = "flexlayout__border_inner_";
    CLASSES["FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER"] = "flexlayout__border_inner_tab_container";
    CLASSES["FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER_"] = "flexlayout__border_inner_tab_container_";
    CLASSES["FLEXLAYOUT__BORDER_TAB_DIVIDER"] = "flexlayout__border_tab_divider";
    CLASSES["FLEXLAYOUT__BORDER_SIZER"] = "flexlayout__border_sizer";
    CLASSES["FLEXLAYOUT__BORDER_TOOLBAR"] = "flexlayout__border_toolbar";
    CLASSES["FLEXLAYOUT__BORDER_TOOLBAR_"] = "flexlayout__border_toolbar_";
    CLASSES["FLEXLAYOUT__BORDER_TOOLBAR_BUTTON"] = "flexlayout__border_toolbar_button";
    CLASSES["FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_FLOAT"] = "flexlayout__border_toolbar_button-float";
    CLASSES["FLEXLAYOUT__DRAG_RECT"] = "flexlayout__drag_rect";
    CLASSES["FLEXLAYOUT__EDGE_RECT"] = "flexlayout__edge_rect";
    CLASSES["FLEXLAYOUT__EDGE_RECT_TOP"] = "flexlayout__edge_rect_top";
    CLASSES["FLEXLAYOUT__EDGE_RECT_LEFT"] = "flexlayout__edge_rect_left";
    CLASSES["FLEXLAYOUT__EDGE_RECT_BOTTOM"] = "flexlayout__edge_rect_bottom";
    CLASSES["FLEXLAYOUT__EDGE_RECT_RIGHT"] = "flexlayout__edge_rect_right";
    CLASSES["FLEXLAYOUT__ERROR_BOUNDARY_CONTAINER"] = "flexlayout__error_boundary_container";
    CLASSES["FLEXLAYOUT__ERROR_BOUNDARY_CONTENT"] = "flexlayout__error_boundary_content";
    CLASSES["FLEXLAYOUT__FLOATING_WINDOW_CONTENT"] = "flexlayout__floating_window_content";
    CLASSES["FLEXLAYOUT__FLOATING_WINDOW_TAB"] = "flexlayout__floating_window_tab";
    CLASSES["FLEXLAYOUT__LAYOUT"] = "flexlayout__layout";
    CLASSES["FLEXLAYOUT__OUTLINE_RECT"] = "flexlayout__outline_rect";
    CLASSES["FLEXLAYOUT__OUTLINE_RECT_EDGE"] = "flexlayout__outline_rect_edge";
    CLASSES["FLEXLAYOUT__SPLITTER"] = "flexlayout__splitter";
    CLASSES["FLEXLAYOUT__SPLITTER_EXTRA"] = "flexlayout__splitter_extra";
    CLASSES["FLEXLAYOUT__SPLITTER_"] = "flexlayout__splitter_";
    CLASSES["FLEXLAYOUT__SPLITTER_BORDER"] = "flexlayout__splitter_border";
    CLASSES["FLEXLAYOUT__SPLITTER_DRAG"] = "flexlayout__splitter_drag";
    CLASSES["FLEXLAYOUT__TAB"] = "flexlayout__tab";
    CLASSES["FLEXLAYOUT__TABSET"] = "flexlayout__tabset";
    CLASSES["FLEXLAYOUT__TABSET_HEADER"] = "flexlayout__tabset_header";
    CLASSES["FLEXLAYOUT__TABSET_HEADER_SIZER"] = "flexlayout__tabset_header_sizer";
    CLASSES["FLEXLAYOUT__TABSET_HEADER_CONTENT"] = "flexlayout__tabset_header_content";
    CLASSES["FLEXLAYOUT__TABSET_MAXIMIZED"] = "flexlayout__tabset-maximized";
    CLASSES["FLEXLAYOUT__TABSET_SELECTED"] = "flexlayout__tabset-selected";
    CLASSES["FLEXLAYOUT__TABSET_SIZER"] = "flexlayout__tabset_sizer";
    CLASSES["FLEXLAYOUT__TABSET_TAB_DIVIDER"] = "flexlayout__tabset_tab_divider";
    CLASSES["FLEXLAYOUT__TABSET_CONTENT"] = "flexlayout__tabset_content";
    CLASSES["FLEXLAYOUT__TABSET_TABBAR_INNER"] = "flexlayout__tabset_tabbar_inner";
    CLASSES["FLEXLAYOUT__TABSET_TABBAR_INNER_"] = "flexlayout__tabset_tabbar_inner_";
    CLASSES["FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER"] = "flexlayout__tabset_tabbar_inner_tab_container";
    CLASSES["FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER_"] = "flexlayout__tabset_tabbar_inner_tab_container_";
    CLASSES["FLEXLAYOUT__TABSET_TABBAR_OUTER"] = "flexlayout__tabset_tabbar_outer";
    CLASSES["FLEXLAYOUT__TABSET_TABBAR_OUTER_"] = "flexlayout__tabset_tabbar_outer_";
    CLASSES["FLEXLAYOUT__TAB_BORDER"] = "flexlayout__tab_border";
    CLASSES["FLEXLAYOUT__TAB_BORDER_"] = "flexlayout__tab_border_";
    CLASSES["FLEXLAYOUT__TAB_BUTTON"] = "flexlayout__tab_button";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_STRETCH"] = "flexlayout__tab_button_stretch";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_CONTENT"] = "flexlayout__tab_button_content";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_LEADING"] = "flexlayout__tab_button_leading";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_OVERFLOW"] = "flexlayout__tab_button_overflow";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT"] = "flexlayout__tab_button_overflow_count";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_TEXTBOX"] = "flexlayout__tab_button_textbox";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_TRAILING"] = "flexlayout__tab_button_trailing";
    CLASSES["FLEXLAYOUT__TAB_BUTTON_STAMP"] = "flexlayout__tab_button_stamp";
    CLASSES["FLEXLAYOUT__TAB_FLOATING"] = "flexlayout__tab_floating";
    CLASSES["FLEXLAYOUT__TAB_FLOATING_INNER"] = "flexlayout__tab_floating_inner";
    CLASSES["FLEXLAYOUT__TAB_TOOLBAR"] = "flexlayout__tab_toolbar";
    CLASSES["FLEXLAYOUT__TAB_TOOLBAR_BUTTON"] = "flexlayout__tab_toolbar_button";
    CLASSES["FLEXLAYOUT__TAB_TOOLBAR_BUTTON_"] = "flexlayout__tab_toolbar_button-";
    CLASSES["FLEXLAYOUT__TAB_TOOLBAR_BUTTON_FLOAT"] = "flexlayout__tab_toolbar_button-float";
    CLASSES["FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER"] = "flexlayout__tab_toolbar_sticky_buttons_container";
    CLASSES["FLEXLAYOUT__TAB_TOOLBAR_BUTTON_CLOSE"] = "flexlayout__tab_toolbar_button-close";
    CLASSES["FLEXLAYOUT__POPUP_MENU_CONTAINER"] = "flexlayout__popup_menu_container";
    CLASSES["FLEXLAYOUT__POPUP_MENU_ITEM"] = "flexlayout__popup_menu_item";
    CLASSES["FLEXLAYOUT__POPUP_MENU"] = "flexlayout__popup_menu";
})(CLASSES = exports.CLASSES || (exports.CLASSES = {}));
//# sourceMappingURL=Types.js.map

/***/ }),

/***/ 6834:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ErrorBoundary = void 0;
const React = __webpack_require__(6540);
const Types_1 = __webpack_require__(6643);
/** @internal */
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }
    static getDerivedStateFromError(error) {
        return { hasError: true };
    }
    componentDidCatch(error, errorInfo) {
        console.debug(error);
        console.debug(errorInfo);
    }
    render() {
        if (this.state.hasError) {
            return (React.createElement("div", { className: Types_1.CLASSES.FLEXLAYOUT__ERROR_BOUNDARY_CONTAINER },
                React.createElement("div", { className: Types_1.CLASSES.FLEXLAYOUT__ERROR_BOUNDARY_CONTENT }, this.props.message)));
        }
        return this.props.children;
    }
}
exports.ErrorBoundary = ErrorBoundary;
//# sourceMappingURL=ErrorBoundary.js.map

/***/ }),

/***/ 6842:
/***/ (function(module) {

/** klay.js version 0.4.1 build 201604131004 */
var klayregister;
var klaycallback;
(function(){
var $wnd, $doc;if(typeof(window) !== 'undefined'){ $wnd = window; $doc = $wnd.document; }
else { $wnd = { Array: function(){} }; }
function kI(){}
function iI(){}
function pb(){}
function Ab(){}
function Tt(){}
function Jt(){}
function Jq(){}
function Vq(){}
function Vs(){}
function yl(){}
function Yl(){}
function gm(){}
function Cu(){}
function tJ(){}
function NJ(){}
function PJ(){}
function PS(){}
function sS(){}
function yS(){}
function AS(){}
function MS(){}
function RS(){}
function TS(){}
function lR(){}
function HR(){}
function IR(){}
function KR(){}
function WR(){}
function AT(){}
function FT(){}
function HT(){}
function JT(){}
function LT(){}
function NT(){}
function sU(){}
function uV(){}
function xV(){}
function EV(){}
function HW(){}
function UX(){}
function XX(){}
function ZX(){}
function _X(){}
function bY(){}
function dY(){}
function wY(){}
function zY(){}
function SY(){}
function VY(){}
function qZ(){}
function tZ(){}
function wZ(){}
function AZ(){}
function d$(){}
function g$(){}
function j$(){}
function w$(){}
function z$(){}
function C$(){}
function F$(){}
function I$(){}
function L$(){}
function N$(){}
function R$(){}
function X$(){}
function _$(){}
function k0(){}
function m0(){}
function s0(){}
function w0(){}
function A0(){}
function C0(){}
function E0(){}
function G0(){}
function V0(){}
function Z0(){}
function _0(){}
function _1(){}
function b1(){}
function e1(){}
function k1(){}
function q1(){}
function u1(){}
function R1(){}
function X1(){}
function Z1(){}
function c2(){}
function f2(){}
function h2(){}
function k2(){}
function n2(){}
function q2(){}
function x2(){}
function A2(){}
function H2(){}
function H4(){}
function z4(){}
function B4(){}
function D4(){}
function U4(){}
function i3(){}
function l3(){}
function u3(){}
function C3(){}
function I3(){}
function $5(){}
function d7(){}
function V7(){}
function q8(){}
function smb(){}
function Wbb(){}
function rcb(){}
function Mcb(){}
function Vdb(){}
function hkb(){}
function Kpb(){}
function Spb(){}
function aqb(){}
function iqb(){}
function pqb(){}
function isb(){}
function mvb(){}
function zwb(){}
function yfb(a){}
function sP(a){}
function XW(a){}
function _t(){Wt()}
function lI(){GP()}
function J8(){G8()}
function m8(){k8()}
function CQ(){zQ()}
function CV(){AV()}
function q0(){p0()}
function S0(){J0()}
function y9(){w9()}
function Bab(){zab()}
function Qab(){Hab()}
function cbb(){abb()}
function sbb(){rbb()}
function Ycb(){Xcb()}
function Wfb(){Mfb()}
function ft(){_s(this)}
function uP(){sP(this)}
function GU(){tU(this)}
function ZW(){XW(this)}
function ic(a){this.a=a}
function sc(a){this.a=a}
function $c(a){this.a=a}
function sf(a){this.a=a}
function Qg(a){this.a=a}
function qh(a){this.a=a}
function Vj(a){this.a=a}
function Nk(a){this.a=a}
function km(a){this.a=a}
function dm(a){this.b=a}
function En(a){this.a=a}
function Hn(a){this.a=a}
function Yp(a){this.a=a}
function bq(a){this.a=a}
function eq(a){this.a=a}
function tq(a){this.a=a}
function wq(a){this.a=a}
function ku(a){this.a=a}
function uu(a){this.a=a}
function Gu(a){this.a=a}
function Uu(a){this.a=a}
function WJ(a){this.a=a}
function rP(a){this.a=a}
function $V(a){this.a=a}
function tW(a){this.a=a}
function yW(a){this.e=a}
function fY(a){this.a=a}
function hY(a){this.a=a}
function lY(a){this.a=a}
function nY(a){this.a=a}
function CY(a){this.a=a}
function JY(a){this.a=a}
function SZ(a){this.a=a}
function Z$(a){this.a=a}
function b_(a){this.a=a}
function d_(a){this.a=a}
function f_(a){this.a=a}
function w1(a){this.a=a}
function y1(a){this.a=a}
function E3(a){this.a=a}
function q4(a){this.a=a}
function x4(a){this.a=a}
function F4(a){this.a=a}
function $8(a){this.a=a}
function a9(a){this.a=a}
function l9(a){this.a=a}
function C9(a){this.a=a}
function k9(a){this.c=a}
function wlb(a){this.a=a}
function nxb(a){this.a=a}
function wcb(a){this.a=a}
function tdb(a){this.a=a}
function ydb(a){this.a=a}
function Ddb(a){this.a=a}
function lkb(a){this.a=a}
function klb(a){this.a=a}
function llb(a){this.a=a}
function inb(a){this.a=a}
function wnb(a){this.d=a}
function Snb(a){this.a=a}
function Ynb(a){this.a=a}
function aob(a){this.a=a}
function fob(a){this.a=a}
function Bob(a){this.b=a}
function Gob(a){this.a=a}
function Mob(a){this.a=a}
function Tob(a){this.c=a}
function opb(a){this.a=a}
function Ipb(a){this.a=a}
function rqb(a){this.a=a}
function zqb(a){this.b=a}
function Nqb(a){this.b=a}
function mrb(a){this.c=a}
function Trb(a){this.a=a}
function Xrb(a){this.a=a}
function Fsb(a){this.a=a}
function ju(){this.a=[]}
function ytb(a){this.a=a}
function Lub(a){this.a=a}
function u5(a){a.b=a.a}
function vg(a){a.c=a.d.d}
function sX(a,b){a.g=b}
function bfb(a,b){a.k=b}
function qfb(a,b){a.a=b}
function rfb(a,b){a.b=b}
function qW(a,b){a.e.k=b}
function qu(a){return a.a}
function yu(a){return a.a}
function Mu(a){return a.a}
function $u(a){return a.a}
function rv(a){return a.a}
function jv(){return null}
function Fu(){return null}
function Rh(){this.c=this}
function tkb(){_s(this)}
function ntb(){Ymb(this)}
function b5(a){a5(this,a)}
function GO(a){IO();$O(a)}
function mI(a){a.a=new aJ}
function IZ(a,b){a.a=b-a.a}
function KZ(a,b){a.b=b-a.b}
function Dq(){Dq=iI;new Jq}
function nW(){nW=iI;new HW}
function ni(){throw new Hmb}
function ii(){throw new Hmb}
function ji(){throw new Hmb}
function li(){throw new Hmb}
function mi(){throw new Hmb}
function dd(){throw new Hmb}
function pj(){throw new Hmb}
function Wn(){throw new Hmb}
function $n(){throw new Hmb}
function qT(){this.a=new GU}
function fU(){this.a=new GU}
function cV(){this.a=new GU}
function pV(){this.a=new GU}
function l7(){this.a=new GU}
function k7(){this.a=new d7}
function A7(){this.a=new n7}
function t8(){this.b=new GU}
function jJ(){aJ.call(this)}
function ZN(){UN.call(this)}
function AP(){uP.call(this)}
function DP(){uP.call(this)}
function q7(){GU.call(this)}
function alb(){ft.call(this)}
function rlb(){ft.call(this)}
function nkb(){ft.call(this)}
function qkb(){ft.call(this)}
function tlb(){ft.call(this)}
function Vlb(){ft.call(this)}
function Hmb(){ft.call(this)}
function Wab(){this.f=new GU}
function Ybb(){this.d=new GU}
function jV(){this.a=new vtb}
function vqb(){throw new Hmb}
function wqb(){throw new Hmb}
function xqb(){throw new Hmb}
function yqb(){throw new Hmb}
function Mqb(){throw new Hmb}
function Uvb(){this.a=new GU}
function it(){it=iI;ht=new pb}
function bmb(){bmb=iI;new smb}
function zb(){zb=iI;yb=new Ab}
function Tq(){Tq=iI;Sq=new Vq}
function dr(){dr=iI;cr=new er}
function Gt(){Gt=iI;Ft=new Jt}
function Bu(){Bu=iI;Au=new Cu}
function fR(){fR=iI;eR=new lR}
function VR(){VR=iI;UR=new WR}
function jS(a){dS(a);return a}
function jl(a){Gi();this.a=a}
function vi(a){hi();this.a=a}
function Uk(a){hi();this.a=a}
function Zk(a){hi();this.a=a}
function ds(a,b){a.i=b;b.f=a}
function ycb(a,b){stb(a.b,b)}
function nsb(){ft.call(this)}
function osb(){ft.call(this)}
function nvb(){ft.call(this)}
function Ccb(){Bcb.call(this)}
function Jcb(){Bcb.call(this)}
function pkb(){nkb.call(this)}
function Xlb(){rlb.call(this)}
function gt(a){et.call(this,a)}
function Vd(a){Md.call(this,a)}
function uh(a){Md.call(this,a)}
function Bk(a){Hj.call(this,a)}
function Jk(a){dk.call(this,a)}
function Lm(a){Em.call(this,a)}
function nq(a){vm.call(this,a)}
function ap(a){Ro.call(this,a)}
function ir(a){Hj.call(this,a)}
function Op(a,b){a.a.W().nb(b)}
function emb(a,b){return a===b}
function Zr(a){return !a?0:a.a}
function Rs(a){return !a?0:a.d}
function Ts(a){return !a?0:a.j}
function zu(a){gt.call(this,a)}
function $J(a){gt.call(this,a)}
function _J(a){gt.call(this,a)}
function EQ(a){_J.call(this,a)}
function Tu(){Uu.call(this,{})}
function y5(a){b5.call(this,a)}
function H5(a){b5.call(this,a)}
function WP(a,b,c){XP(a,b.b,c)}
function a7(a,b,c){f6(a.c,b,c)}
function qV(a,b,c){a.b.Fc(b,c)}
function M9(a){$8.call(this,a)}
function P9(a){$8.call(this,a)}
function YY(){this.a=(sK(),qK)}
function cZ(){this.a=(sK(),qK)}
function vtb(){this.a=new ntb}
function Vwb(){this.a=new iwb}
function vT(){vT=iI;uT=new AT}
function AV(){AV=iI;zV=new EV}
function p0(){p0=iI;o0=new s0}
function Ckb(a){xkb();return a}
function Ixb(a){Dxb(a);return a}
function ikb(a){et.call(this,a)}
function okb(a){gt.call(this,a)}
function slb(a){gt.call(this,a)}
function Kb(a){this.c=$v(_b(a))}
function FI(){this.a=0;this.b=0}
function aJ(){OI(this);_I(this)}
function cI(){aI==null&&(aI=[])}
function Vvb(a){a.b=null;a.c=0}
function mS(a,b){a.b=b;return a}
function nS(a,b){a.c=b;return a}
function oS(a,b){a.f=b;return a}
function pS(a,b){a.g=b;return a}
function S7(a,b){a.a=b;return a}
function T7(a,b){a.f=b;return a}
function U7(a,b){a.k=b;return a}
function xc(a,b){return a.e-b.e}
function H3(a,b){return a.d-b.d}
function Klb(a){return a<0?-a:a}
function hlb(a){return isNaN(a)}
function gv(a){return new Gu(a)}
function iv(a){return new lv(a)}
function rkb(a){gt.call(this,a)}
function ulb(a){gt.call(this,a)}
function Ulb(a){gt.call(this,a)}
function Wlb(a){gt.call(this,a)}
function Imb(a){gt.call(this,a)}
function et(a){this.f=a;_s(this)}
function _2(){this.b=0;this.a=0}
function Ws(){Ws=iI;Math.log(2)}
function Ytb(){Ytb=iI;Xtb=$tb()}
function Vtb(c,a,b){c.set(a,b)}
function Wtb(c,a,b){c.set(a,b)}
function Ot(a,b){Nt();Mt.dc(a,b)}
function tv(a,b){return Skb(a,b)}
function zm(a,b){return a.a.B(b)}
function aP(a,b){return a.g[b.e]}
function bP(a,b){return a.i[b.e]}
function cP(a,b){return a.j[b.e]}
function dP(a,b){return a.n[b.e]}
function eP(a,b){return a.o[b.e]}
function Ou(b,a){return a in b.a}
function Tab(a,b){return a.b-b.b}
function ndb(a,b){return a.d-b.d}
function jgb(a,b){return a.i-b.i}
function Nlb(a,b){return a>b?a:b}
function Olb(a,b){return a>b?a:b}
function Plb(a,b){return a>b?a:b}
function Qlb(a,b){return a<b?a:b}
function Rlb(a,b){return a<b?a:b}
function Slb(a,b){return a<b?a:b}
function awb(a){return !!a&&a.b}
function $ob(a){_ob(a,a.length)}
function bpb(a){apb(a,a.length)}
function dpb(a){cpb(a,a.length)}
function Cmb(a){okb.call(this,a)}
function Bmb(a){lkb.call(this,a)}
function oxb(a){nxb.call(this,a)}
function Ylb(a){slb.call(this,a)}
function Frb(a){zqb.call(this,a)}
function Nrb(a){Frb.call(this,a)}
function csb(a){Rqb.call(this,a)}
function zmb(){lkb.call(this,'')}
function Amb(){lkb.call(this,'')}
function Ikb(a){Gkb(a);return a.n}
function Jkb(a){Gkb(a);return a.j}
function Hkb(a){return a.e&&a.e()}
function Lk(a,b){return a.a.sb(b)}
function Sb(a,b){return a?a:_b(b)}
function vW(a,b){return rJ(a.a,b)}
function w4(a,b){return t4(a.a,b)}
function VH(a,b){return RH(a,b)<0}
function Dlb(a){return bmb(),''+a}
function qe(a){return !a?null:a.d}
function Gr(a){hi();this.a=_b(a)}
function I9(){F9();this.g=new Um}
function J0(){J0=iI;I0=(kP(),hP)}
function Et(){ut!=0&&(ut=0);wt=-1}
function bS(a){cS(a,a.d);return a}
function i7(a,b){a.a.d=b;return a}
function g7(a,b){a.a.a=b;return a}
function h7(a,b){a.a.c=b;return a}
function j7(a,b){a.a.f=b;return a}
function z7(a,b){a.a.f=b;return a}
function y7(a,b){a.a.b=b;return a}
function hxb(a,b,c){a.splice(b,c)}
function oqb(a,b){return Akb(b,a)}
function Drb(a,b){return a.b.t(b)}
function jrb(a,b){return a.c.t(b)}
function ttb(a,b){return a.a.R(b)}
function Ttb(b,a){return b.get(a)}
function Utb(b,a){return b.get(a)}
function elb(a,b){return a.test(b)}
function Jlb(a){return a<=0?0-a:a}
function ilb(a){return bmb(),''+a}
function qlb(a){return bmb(),''+a}
function wtb(a){this.a=new otb(a)}
function Wwb(a){this.a=new jwb(a)}
function nc(a){this.a=Wv(_b(a),19)}
function Bf(a){this.b=Wv(_b(a),57)}
function Ch(a){this.d=Wv(_b(a),56)}
function Ac(a,b){this.d=a;this.e=b}
function Ie(a,b){this.b=a;this.a=b}
function tm(a,b){this.b=a;this.a=b}
function Pf(a,b){this.b=a;this.c=b}
function Fk(a,b){this.a=a;this.b=b}
function Bn(a,b){this.a=a;this.b=b}
function Sn(a,b){this.a=a;this.f=b}
function Mc(a,b){Ac.call(this,a,b)}
function Hh(a,b){Ac.call(this,a,b)}
function yp(a,b){Ac.call(this,a,b)}
function bp(a,b){this.b=a;this.c=b}
function Oq(a,b){this.e=a;this.c=b}
function Yq(a,b){this.a=a;this.b=b}
function fs(a,b){this.a=a;this.b=b}
function rs(a,b){Ac.call(this,a,b)}
function _u(a,b){this.a=a;this.b=b}
function Mo(a){this.a=Wv(_b(a),20)}
function Ro(a){this.a=Wv(_b(a),20)}
function Fp(a){this.a=Wv(_b(a),57)}
function vm(a){this.b=Wv(_b(a),35)}
function HI(a,b){this.a=a;this.b=b}
function RJ(a,b){this.a=a;this.b=b}
function jK(a,b){Ac.call(this,a,b)}
function Qm(a,b){return Qmb(a.b,b)}
function fv(a){return tu(),a?su:ru}
function tK(a){return a==oK||a==pK}
function uK(a){return a==rK||a==nK}
function RI(a,b){TI(a,b,a.a,a.a.a)}
function SI(a,b){TI(a,b,a.c.b,a.c)}
function wK(a,b){Ac.call(this,a,b)}
function FK(a,b){Ac.call(this,a,b)}
function OK(a,b){Ac.call(this,a,b)}
function ZK(a,b){Ac.call(this,a,b)}
function fL(a,b){Ac.call(this,a,b)}
function pM(a,b){Ac.call(this,a,b)}
function AM(a,b){Ac.call(this,a,b)}
function NM(a,b){Ac.call(this,a,b)}
function VM(a,b){Ac.call(this,a,b)}
function uN(a,b){Ac.call(this,a,b)}
function EN(a,b){Ac.call(this,a,b)}
function NN(a,b){Ac.call(this,a,b)}
function EO(a,b){Ac.call(this,a,b)}
function lP(a,b){Ac.call(this,a,b)}
function OS(a,b){this.b=a;this.a=b}
function VS(a,b){this.c=a;this.d=b}
function wW(a,b){this.a=a;this.c=b}
function BW(a,b){this.e=a;this.c=b}
function FW(a,b){this.e=a;this.d=b}
function fT(a,b){Ac.call(this,a,b)}
function DX(a,b){Ac.call(this,a,b)}
function MY(a,b){this.a=a;this.b=b}
function PY(a,b){this.a=a;this.b=b}
function YZ(a,b){Ac.call(this,a,b)}
function f0(a,b){Ac.call(this,a,b)}
function J1(a,b){Ac.call(this,a,b)}
function Y3(a,b){Ac.call(this,a,b)}
function h4(a,b){Ac.call(this,a,b)}
function $7(a,b){Ac.call(this,a,b)}
function y8(a,b){Ac.call(this,a,b)}
function q9(a,b){Ac.call(this,a,b)}
function MR(a,b){return Zsb(a.c,b)}
function Bnb(a){return a.b<a.d.Y()}
function Zmb(a){return a.d.c+a.e.c}
function hrb(a,b){return a.c.ab(b)}
function Brb(a,b){return a.b.kb(b)}
function Crb(a,b){return a.b.lb(b)}
function Erb(a,b){return a.b.pb(b)}
function Irb(a,b){return a.b.kb(b)}
function Jrb(a,b){return a.b.lb(b)}
function dT(a){return a==$S||a==bT}
function eT(a){return a==$S||a==_S}
function MM(a){return a!=IM&&a!=JM}
function lg(a){return Yf(a),a.d.Y()}
function jtb(a){this.c=a;gtb(this)}
function otb(a){$mb.call(this,a,0)}
function iwb(){jwb.call(this,null)}
function xk(){uh.call(this,new ntb)}
function Ap(){yp.call(this,'KEY',0)}
function lr(a){kr();dk.call(this,a)}
function Dt(a){$wnd.clearTimeout(a)}
function um(a){return a.Vb(a.b.H())}
function Pp(a){this.a=Wv(_b(a),144)}
function Um(){this.b=(mp(),new ntb)}
function hsb(){hsb=iI;gsb=new isb}
function Rpb(){Rpb=iI;Qpb=new Spb}
function nqb(){nqb=iI;mqb=new pqb}
function hc(){hc=iI;gc=new Kb(',')}
function nJ(){nJ=iI;Math.pow(2,-65)}
function UN(){VN.call(this,0,0,0,0)}
function wab(a,b){Ac.call(this,a,b)}
function lbb(a,b){Ac.call(this,a,b)}
function Hbb(a,b){Ac.call(this,a,b)}
function Mbb(a,b){Ac.call(this,a,b)}
function xQ(a){wJ();CJ.call(this,a)}
function mcb(a,b){Ac.call(this,a,b)}
function gab(a,b){this.c=a;this.b=b}
function Qbb(a,b){this.a=a;this.b=b}
function Fcb(a,b){this.b=a;this.d=b}
function ggb(a,b){Ac.call(this,a,b)}
function Agb(a,b){Ac.call(this,a,b)}
function Igb(a,b){Ac.call(this,a,b)}
function Rgb(a,b){Ac.call(this,a,b)}
function ahb(a,b){Ac.call(this,a,b)}
function phb(a,b){Ac.call(this,a,b)}
function Ihb(a,b){Ac.call(this,a,b)}
function Nhb(a,b){Ac.call(this,a,b)}
function Yib(a,b){Ac.call(this,a,b)}
function ejb(a,b){Ac.call(this,a,b)}
function Rjb(a,b){Ac.call(this,a,b)}
function dkb(a,b){Ac.call(this,a,b)}
function fxb(a,b,c){a.splice(b,0,c)}
function Yjb(a,b,c){a.g[b.e][b.e]=c}
function D6(a,b){a.a=b;a.g=0;a.f=0}
function BI(a){a.a=0;a.b=0;return a}
function rY(a){return zU(a.b.c,a,0)}
function Llb(a){return Math.ceil(a)}
function Tlb(a){return Math.sqrt(a)}
function cub(a,b){return Utb(a.a,b)}
function vob(a,b){return !!Wvb(a,b)}
function Yob(a,b){Zob(a,a.length,b)}
function Gwb(a,b){Ac.call(this,a,b)}
function Psb(a,b){this.b=a;this.a=b}
function qob(a,b){this.d=a;this.e=b}
function dcb(){$bb();this.c=new vtb}
function Rdb(){Ndb();this.a=new vtb}
function aub(){Ytb();return new Xtb}
function Xb(a){if(!a){throw new rlb}}
function dc(a){if(!a){throw new tlb}}
function Vm(a){if(!a){throw new nvb}}
function SV(){this.b=(mp(),new ntb)}
function Q4(){this.b=(mp(),new ntb)}
function II(a){this.a=a.a;this.b=a.b}
function gw(a){return a==null?null:a}
function re(a){return !a?null:a.zb()}
function $i(a,b){return a.Nb().sb(b)}
function aq(a,b){return a.a.a.a.U(b)}
function nl(a,b){return Ll(a.mb(),b)}
function B3(a,b){return glb(b.b,a.b)}
function h3(a,b){return glb(b.k,a.k)}
function Mlb(a){return Math.floor(a)}
function vmb(a,b){return a.a+=''+b,a}
function xmb(a,b){a.a+=''+b;return a}
function ymb(a,b){a.a+=''+b;return a}
function iw(a){Hxb(a==null);return a}
function T2(a){a.d&&Z2(a);return a.a}
function U2(a){a.d&&Z2(a);return a.b}
function V2(a){a.d&&Z2(a);return a.c}
function Tvb(a,b){vU(a.a,b);return b}
function ptb(a){Ymb(this);he(this,a)}
function _4(a){this.c=a;this.e=false}
function Jh(){Hh.call(this,'OPEN',0)}
function ts(){rs.call(this,'SIZE',0)}
function qxb(){nxb.call(this,'UTF-8')}
function Nxb(){Nxb=iI;Kxb={};Mxb={}}
function IO(){IO=iI;HO=new DJ(yzb,0)}
function Sh(a){_b(a);return new Vh(a)}
function pmb(a){bmb();return a.length}
function Jmb(a,b){return cmb(a.a,b.a)}
function vlb(a,b){return xlb(a.a,b.a)}
function Ys(a,b){return a==b?0:a?1:-1}
function Cs(a){return Rs(a.e)-Rs(a.g)}
function xI(a){return new HI(a.a,a.b)}
function RN(a){return new HI(a.d,a.e)}
function tU(a){a.c=xv(UF,syb,1,0,4,1)}
function Cp(){yp.call(this,'VALUE',1)}
function dX(a){cX.call(this);this.a=a}
function Q2(a){this.a=new $2;this.b=a}
function Vh(a){this.a=a;Rh.call(this)}
function vl(a){this.a=a;Rh.call(this)}
function U8(){P8();this.d=(ckb(),bkb)}
function zxb(a){if(!a){throw new qkb}}
function uxb(a){if(!a){throw new tlb}}
function vxb(a){if(!a){throw new rlb}}
function Hxb(a){if(!a){throw new alb}}
function Bxb(a){if(!a){throw new nvb}}
function Wub(){ytb.call(this,new wub)}
function Kh(){Hh.call(this,'CLOSED',1)}
function Im(a){Em.call(this,new Lm(a))}
function p7(a,b){++a.d;return BU(a,b)}
function kkb(a,b){return gmb(a.a,0,b)}
function jlb(a,b){return glb(a.a,b.a)}
function Al(a){return Pl(a.b.mb(),a.a)}
function Dl(a){return Wl(a.a.mb(),a.b)}
function q6(a,b){return b==a.c?a.d:a.c}
function Zs(a,b){return a<b?-1:a>b?1:0}
function xlb(a,b){return a<b?-1:a>b?1:0}
function pvb(a){return a!=null?vb(a):0}
function Ntb(a){this.a=aub();this.b=a}
function fub(a){this.a=aub();this.b=a}
function Cg(a){this.a=a;xg.call(this,a)}
function o4(){n4();this.b=new q4(this)}
function Oh(){Oh=iI;Nh=Jb(new Kb(', '))}
function Gh(){Gh=iI;Fh=new Jh;Eh=new Kh}
function Il(){Il=iI;Gl=new Yl;Hl=new gm}
function xp(){xp=iI;vp=new Ap;wp=new Cp}
function qs(){qs=iI;ps=new ts;os=new ws}
function wJ(){wJ=iI;uJ=new NJ;vJ=new PJ}
function Teb(a){a.g=new GU;a.b=new GU}
function OI(a){a.a=new mvb;a.c=new mvb}
function n4(){n4=iI;m4=new U4;l4=new u4}
function Uc(){Mc.call(this,'IS_NULL',2)}
function Kwb(){Gwb.call(this,'Head',1)}
function Pwb(){Gwb.call(this,'Tail',3)}
function pR(a,b){qR.call(this,a,b,null)}
function lpb(a,b){ipb(a,0,a.length,b)}
function x7(a,b){vU(b.a,a.a);return a.a}
function CI(a,b){a.a*=b;a.b*=b;return a}
function gl(a,b){Gi();this.a=a;this.b=b}
function i9(a,b){return a.a[b.d.k][b.k]}
function W9(a,b){return a.a[b.d.k][b.k]}
function xJ(a,b){return kmb(a.b,b.mc())}
function Swb(a,b){return qe(Xvb(a.a,b))}
function Twb(a,b){return qe(Yvb(a.a,b))}
function $T(a,b){return Wv(Dd(a.a,b),20)}
function aw(a,b){return a!=null&&Vv(a,b)}
function Qob(a){return a.a<a.c.c.length}
function htb(a){return a.a<a.c.a.length}
function y$(a,b){return glb(a.i.a,b.i.a)}
function S$(a,b){return a.i.b=(Dxb(b),b)}
function T$(a,b){return a.i.b=(Dxb(b),b)}
function utb(a,b){return a.a.eb(b)!=null}
function Vjb(a,b,c){return a.g[b.e][c.e]}
function Bkb(a){xkb();return bmb(),''+a}
function Mwb(){Gwb.call(this,'Range',2)}
function ws(){rs.call(this,'DISTINCT',1)}
function Xc(){Mc.call(this,'NOT_NULL',3)}
function mp(){mp=iI;lp=new Rb((Oh(),Nh))}
function Hj(a){this.d=(ypb(),new mrb(a))}
function Hb(a,b){return Gb(a,new zmb,b).a}
function Mb(a,b){return b==null?a.b:Ib(b)}
function mt(a){return a==null?null:a.name}
function cw(a){return typeof a==='number'}
function ew(a){return typeof a==='string'}
function Hi(a,b){return new Mk(a,a.Y(),b)}
function An(a,b){return new no(a.a,a.b,b)}
function Jb(a){_b(Wxb);return new Nb(a,a)}
function Do(a){Mh(a,Vyb);return new HU(a)}
function Am(a,b){this.a=b;vm.call(this,a)}
function tp(a,b){this.a=b;vm.call(this,a)}
function If(a,b){this.a=a;Bf.call(this,b)}
function ks(a){this.c=a;this.a=Qr(this.c)}
function MZ(a){var b;b=a.a;a.a=a.b;a.b=b}
function pW(a,b){a.e.j.a=b.a;a.e.j.b=b.b}
function xvb(a,b,c){a.a=b^1502;a.b=c^_Ab}
function uI(a,b,c){a.a+=b;a.b+=c;return a}
function DI(a,b,c){a.a-=b;a.b-=c;return a}
function zI(a){a.a=-a.a;a.b=-a.b;return a}
function UI(a){Bxb(a.b!=0);return a.a.a.c}
function VI(a){Bxb(a.b!=0);return a.c.b.c}
function uub(a,b){if(a.a){Hub(b);Gub(b)}}
function rn(a,b,c){var d;d=a.ub(b);d.J(c)}
function Iq(a,b){return Zs(b.Yb(),a.Yb())}
function o5(a){return Wv(yU(a.a,a.b),128)}
function EU(a){return cxb(a.c,a.c.length)}
function Fv(a){return a.l+a.m*czb+a.h*dzb}
function LM(a){return a==EM||a==GM||a==FM}
function UH(a){return typeof a==='number'}
function Zsb(a,b){return !!b&&a.b[b.e]==b}
function lsb(a,b){var c;c=a[WAb];b[WAb]=c}
function FQ(a,b){_J.call(this,a);this.b=b}
function Rqb(a){zqb.call(this,a);this.a=a}
function arb(a){Nqb.call(this,a);this.a=a}
function dsb(a){Frb.call(this,a);this.a=a}
function Xub(a){ytb.call(this,new xub(a))}
function wwb(a){this.a=a;Bob.call(this,a)}
function v5(a){this.c=a;this.a=1;this.b=1}
function Rb(a){this.a=a;this.b=$v(_b('='))}
function B5(){this.a=new aJ;this.e=new aJ}
function tV(){this.a=new fU;this.c=new uV}
function cX(){this.i=new FI;this.j=new FI}
function Md(a){Xb(a.d.c+a.e.c==0);this.b=a}
function _s(a){a.g=null;Ot(a,a.f);return a}
function Nl(a){Il();_b(a);return new om(a)}
function St(a){Nt();return parseInt(a)||-1}
function Uwb(a,b){return cwb(a.a,b)!=null}
function ok(a,b){return !rk(a,b)&&!qk(a,b)}
function txb(a){return a.$H||(a.$H=++sxb)}
function yc(a){return a.d!=null?a.d:''+a.e}
function zc(a){return a.d!=null?a.d:''+a.e}
function pwb(a){return a.b=Wv(Cnb(a.a),21)}
function bw(a){return typeof a==='boolean'}
function pub(a){a.b=new Iub(a);a.c=new ntb}
function oab(){this.a=new GU;this.d=new GU}
function Iub(a){Jub.call(this,a,null,null)}
function ug(a,b,c,d){mg.call(this,a,b,c,d)}
function BP(a,b,c,d){vP.call(this,a,b,c,d)}
function EP(a,b,c,d){vP.call(this,a,b,c,d)}
function Kg(a,b,c){_f.call(this,a,b,c,null)}
function Lg(a,b,c){_f.call(this,a,b,c,null)}
function es(a,b,c){a.i=b;b.f=a;b.i=c;c.f=b}
function tI(a,b){mI(this);this.e=a;this.f=b}
function yg(a,b){this.d=a;vg(this);this.b=b}
function kJ(a){OI(this);_I(this);Ue(this,a)}
function Xv(a){Hxb(a==null||bw(a));return a}
function Yv(a){Hxb(a==null||cw(a));return a}
function $v(a){Hxb(a==null||ew(a));return a}
function vI(a,b){a.a+=b.a;a.b+=b.b;return a}
function EI(a,b){a.a-=b.a;a.b-=b.b;return a}
function U$(a,b){return a.i.a=(Dxb(b),b)+10}
function V$(a,b){return a.i.a=(Dxb(b),b)+10}
function h6(a,b){return Wv(Smb(a.k,b),24).a}
function Bj(a,b){return Lh(a,b),new zr(a,b)}
function Web(a,b){return Wv(a.b.sb(b),92).a}
function WX(a){return Wv(a,7).b.c.length!=0}
function TX(a){return Wv(a,7).e.c.length!=0}
function jX(a){return !a.d?-1:zU(a.d.a,a,0)}
function lt(a){return a==null?null:a.message}
function Gkb(a){if(a.n!=null){return}Wkb(a)}
function wmb(a,b,c,d){jkb(a,b,c,d);return a}
function mmb(a,b){bmb();return a.indexOf(b)}
function QX(a,b){if(!b){throw new Vlb}a.g=b}
function Mn(a){if(a.e.c!=a.b){throw new nsb}}
function Xn(a){if(a.f.c!=a.b){throw new nsb}}
function Uq(a,b){_b(a);_b(b);return Akb(a,b)}
function U6(a,b){this.a=a;this.c=b;this.b=2}
function sI(){mI(this);this.e=-1;this.f=true}
function Dh(){Vd.call(this,new ntb);this.a=3}
function CP(a){vP.call(this,a.d,a.b,a.a,a.c)}
function FP(a){vP.call(this,a.d,a.b,a.a,a.c)}
function r6(a){k6.call(this,a);this.c=new GU}
function Oc(){Mc.call(this,'ALWAYS_TRUE',0)}
function Rc(){Mc.call(this,'ALWAYS_FALSE',1)}
function _T(a){XT();this.a=new Dh;YT(this,a)}
function Y9(a){!a.e&&(a.e=new GU);return a.e}
function W7(a){var b;b=new V7;b.e=a;return b}
function msb(a){var b;b=a[WAb]|0;a[WAb]=b+1}
function Anb(a,b){a.a.rb(a.b,b);++a.b;a.c=-1}
function Enb(a,b){uxb(a.c!=-1);a.a.wb(a.c,b)}
function zkb(a,b){xkb();return a==b?0:a?1:-1}
function Wjb(a,b,c){return a.g[b.e][c.e]*a.d}
function xt(a,b,c){return a.apply(b,c);// removed by dead control flow
{ var d; }}
function ssb(a,b,c){return rsb(a,Wv(b,17),c)}
function m5(a,b){return b==(sN(),rN)?a.c:a.d}
function Zi(a,b){return b!=null&&a.Nb().kb(b)}
function skb(a,b){this.e=b;this.f=a;_s(this)}
function om(a){this.b=a;this.a=(Il(),Il(),Hl)}
function dk(a){hi();this.a=(ypb(),new Frb(a))}
function hi(){hi=iI;new vi((ypb(),ypb(),vpb))}
function e8(){e8=iI;d8=PQ(new WQ,(d0(),X_))}
function rwb(a){swb.call(this,a,(Fwb(),Bwb))}
function IU(a){tU(this);gxb(this.c,0,a.ob())}
function tr(a,b,c){this.b=a;this.a=b;this.c=c}
function WS(a,b,c){VS.call(this,a,b);this.b=c}
function XV(a,b,c){this.b=a;this.a=b;this.c=c}
function job(a,b){var c;c=a.e;a.e=b;return c}
function qub(a){Ymb(a.c);a.b.b=a.b;a.b.a=a.b}
function Vf(a){a.b?Vf(a.b):Umb(a.f.b,a.e,a.d)}
function YI(a){Bxb(a.b!=0);return $I(a,a.a.a)}
function ZI(a){Bxb(a.b!=0);return $I(a,a.c.b)}
function Wl(a,b){Il();_b(b);return new Am(a,b)}
function np(a,b){mp();return new tp(a.mb(),b)}
function jmb(a,b){bmb();return a.charCodeAt(b)}
function imb(a,b,c){bmb();return a.substr(b,c)}
function qmb(a){bmb();return a==null?Wxb:xb(a)}
function Xjb(a,b,c){return Vjb(a,b.g,c.g)*a.d}
function Ev(a,b,c){return {'l':a,'m':b,'h':c}}
function YU(a,b){return ZU(a,new VS(b.a,b.b))}
function SN(a,b,c,d,e){a.d=b;a.e=c;a.c=d;a.b=e}
function wS(a,b,c,d,e){a.b=b;a.c=c;a.d=d;a.a=e}
function QI(a,b){TI(a,b,a.c.b,a.c);return true}
function vU(a,b){a.c[a.c.length]=b;return true}
function DJ(a,b){wJ();CJ.call(this,a);this.a=b}
function g8(){e8();this.e=new aJ;this.d=new aJ}
function Fmb(){Fmb=iI;Dmb=new hkb;Emb=new hkb}
function zab(){zab=iI;yab=VQ(new WQ,(d0(),v_))}
function abb(){abb=iI;_ab=VQ(new WQ,(d0(),v_))}
function rbb(){rbb=iI;qbb=VQ(new WQ,(d0(),v_))}
function $bb(){$bb=iI;Zbb=VQ(new WQ,(d0(),v_))}
function Wt(){Wt=iI;Error.stackTraceLimit=64}
function xS(){wS(this,false,false,false,false)}
function Bo(a){var b;b=new GU;Jl(b,a);return b}
function Eo(a){var b;b=new aJ;ml(b,a);return b}
function XQ(a){var b;b=new WQ;QQ(b,a);return b}
function Ocb(a){var b;b=new Mcb;b.a=a;return b}
function Wv(a,b){Hxb(a==null||Vv(a,b));return a}
function Dvb(a,b){if(a<0||a>=b){throw new pkb}}
function pl(a,b){_b(a);_b(b);return new Bl(a,b)}
function ul(a,b){_b(a);_b(b);return new El(a,b)}
function nmb(a,b){bmb();return a.lastIndexOf(b)}
function rgb(a,b,c){return a<b?c<=a:a<=c||a==b}
function cvb(a,b,c){this.d=a;this.b=c;this.a=b}
function atb(a,b,c){this.a=a;this.b=b;this.c=c}
function lub(a,b,c){this.a=a;this.b=b;this.c=c}
function Nb(a,b){this.a=a;this.b=Wxb;this.c=b.c}
function z3(a){this.c=a.c;this.a=a.e;this.b=a.b}
function xg(a){this.d=a;vg(this);this.b=Ed(a.d)}
function u4(){FS.call(this);this.a=new x4(this)}
function FS(){this.c=new PS;this.d=new KS(this)}
function qr(a){var b;b=new vtb;Jl(b,a);return b}
function qwb(a){vnb(a.a);dwb(a.c,a.b);a.b=null}
function n5(a){return a.c-Wv(yU(a.a,a.b),128).b}
function t5(a,b){return a.c<b.c?-1:a.c==b.c?0:1}
function t4(a,b){return tK(a.b.d)?b.xc():b.wc()}
function gmb(a,b,c){return bmb(),a.substr(b,c-b)}
function gxb(a,b,c){dxb(c,0,a,b,c.length,false)}
function Jub(a,b,c){this.c=a;qob.call(this,b,c)}
function Bl(a,b){this.b=a;this.a=b;Rh.call(this)}
function El(a,b){this.a=a;this.b=b;Rh.call(this)}
function Lq(a,b){this.b=a;this.a=b;Mh(b,'count')}
function dl(a){this.b=a;this.a=nj(this.b.a).Kb()}
function CJ(a){wJ();this.c=uJ;this.d=vJ;this.b=a}
function iab(a,b,c){gab.call(this,a,b);this.a=c}
function mab(a,b,c){gab.call(this,a,b);this.a=c}
function yU(a,b){Cxb(b,a.c.length);return a.c[b]}
function PQ(a,b){Wv(yU(a.a,5),18).ib(b);return a}
function RQ(a,b){Wv(yU(a.a,0),18).ib(b);return a}
function SQ(a,b){Wv(yU(a.a,1),18).ib(b);return a}
function TQ(a,b){Wv(yU(a.a,2),18).ib(b);return a}
function UQ(a,b){Wv(yU(a.a,3),18).ib(b);return a}
function VQ(a,b){Wv(yU(a.a,4),18).ib(b);return a}
function iS(a){gS(a,(sK(),oK));a.e=true;return a}
function Pt(a){Nt();var b;b=Mt.ec(a);return Qt(b)}
function Pkb(a,b){var c;c=Mkb(a,b);c.g=2;return c}
function _ob(a,b){var c;for(c=0;c<b;++c){a[c]=0}}
function YW(a,b){a.b=b.b;a.c=b.c;a.d=b.d;a.a=b.a}
function Hub(a){a.a.b=a.b;a.b.a=a.a;a.a=a.b=null}
function NX(a){return a.b.c.length+a.e.c.length}
function zv(a){return Array.isArray(a)&&a.ad===kI}
function ol(a,b){return Il(),Tl(new Tob(a),b)!=-1}
function vv(a,b,c,d,e,f){return wv(a,b,c,d,e,0,f)}
function BJ(a,b,c){wJ();FJ.call(this,a.b,b,c,a.d)}
function AJ(a,b){wJ();FJ.call(this,a.b,b,a.c,a.d)}
function uU(a,b,c){Fxb(b,a.c.length);fxb(a.c,b,c)}
function mpb(a,b){Cxb(b,a.a.length);return a.a[b]}
function kpb(c){c.sort(function(a,b){return a-b})}
function _b(a){if(a==null){throw new Vlb}return a}
function lv(a){if(a==null){throw new Vlb}this.a=a}
function Us(a,b,c){if(a.a!=b){throw new nsb}a.a=c}
function wxb(a,b){if(!a){throw new slb((bmb(),b))}}
function Axb(a,b){if(!a){throw new rkb((bmb(),b))}}
function Dxb(a){if(a==null){throw new Vlb}return a}
function Yub(a){ytb.call(this,new wub);Ue(this,a)}
function xtb(a){this.a=new otb(a.Y());Ue(this,a)}
function Lsb(a){this.c=a;this.a=new jtb(this.c.a)}
function Er(a){Gi();this.a=(ypb(),new rqb(_b(a)))}
function xkb(){xkb=iI;vkb=(xkb(),false);wkb=true}
function Glb(){Glb=iI;Flb=xv(PF,Txb,24,256,0,1)}
function k8(){k8=iI;j8=PQ(RQ(new WQ,(d0(),z_)),X_)}
function aS(){aS=iI;ZR=new yS;_R=new FS;$R=new AS}
function dw(a){return a!=null&&fw(a)&&!(a.ad===kI)}
function _v(a){return !Array.isArray(a)&&a.ad===kI}
function Wmb(a,b){return ew(b)?Xmb(a,b):Mtb(a.d,b)}
function Ysb(a,b){return aw(b,17)&&Zsb(a,Wv(b,17))}
function $sb(a,b){return aw(b,17)&&_sb(a,Wv(b,17))}
function bub(a,b){return !(Utb(a.a,b)===undefined)}
function Vsb(a,b){var c;c=Usb(a);zpb(c,b);return c}
function Kt(a,b){!a&&(a=[]);a[a.length]=b;return a}
function rsb(a,b,c){Wsb(a.a,b);return usb(a,b.e,c)}
function omb(a,b,c){bmb();return a.lastIndexOf(b,c)}
function xxb(a,b,c){if(!a){throw new slb(Jxb(b,c))}}
function Zob(a,b,c){var d;for(d=0;d<b;++d){a[d]=c}}
function Qo(a,b){var c;c=a.a.Y();bc(b,c);return c-b}
function ud(a){var b;b=a.i;return !b?(a.i=a.T()):b}
function Ae(a){var b;b=a.c;return !b?(a.c=a.gb()):b}
function ki(a){var b;b=a.c;return !b?(a.c=a.Jb()):b}
function nj(a){if(a.e){return a.e}return a.e=a.Ob()}
function oj(a){if(a.f){return a.f}return a.f=a.Pb()}
function Hv(a,b){return Ev(a.l&b.l,a.m&b.m,a.h&b.h)}
function flb(a,b){return glb((Dxb(a),a),(Dxb(b),b))}
function Ed(a){return aw(a,20)?Wv(a,20).tb():a.mb()}
function Ml(a){Il();_b(a);while(a.G()){a.H();a.I()}}
function Uab(a){var b;b=a;while(b.g){b=b.g}return b}
function LY(a){a.b.i.a+=a.a.f*(a.a.a-1);return null}
function Sob(a){uxb(a.b!=-1);a.c.vb(a.a=a.b);a.b=-1}
function Dnb(a){Bxb(a.b>0);return a.a.sb(a.c=--a.b)}
function $f(a){a.b?$f(a.b):a.d.V()&&Wmb(a.f.b,a.e)}
function wg(a){Yf(a.d);if(a.d.d!=a.c){throw new nsb}}
function ksb(a,b){if(b[WAb]!=a[WAb]){throw new nsb}}
function Pl(a,b){Il();_b(a);_b(b);return new tm(a,b)}
function Zq(a,b){Gi();Yq.call(this,a,Yi(new opb(b)))}
function mg(a,b,c,d){this.a=a;_f.call(this,a,b,c,d)}
function GI(a){this.a=Math.cos(a);this.b=Math.sin(a)}
function GQ(a,b,c){_J.call(this,a);this.b=b;this.a=c}
function NR(a){this.b=new GU;this.a=new GU;this.c=a}
function sY(a){this.c=new FI;this.a=new GU;this.b=a}
function tu(){tu=iI;ru=new uu(false);su=new uu(true)}
function o7(a,b){++a.d;return a.c[a.c.length]=b,true}
function $ub(a,b){TI(a.d,b,a.b.b,a.b);++a.a;a.c=null}
function stb(a,b){var c;c=a.a.db(b,a);return c==null}
function cxb(a,b){var c;c=a.slice(0,b);return Cv(c,a)}
function exb(a,b){var c;c=new Array(b);return Cv(c,a)}
function usb(a,b,c){var d;d=a.b[b];a.b[b]=c;return d}
function apb(a,b){var c;for(c=0;c<b;++c){a[c]=null}}
function cpb(a,b){var c;for(c=0;c<b;++c){a[c]=false}}
function r1(a,b){return xkb(),Wv(b.b,24).a<a?wkb:vkb}
function s1(a,b){return xkb(),Wv(b.a,24).a<a?wkb:vkb}
function Tk(a,b){return Wv(ki(nj(a.a)).sb(b),21).yb()}
function dq(a){return mp(),Wl(Rm(a.a).mb(),(xp(),vp))}
function Uh(a){return Il(),new Im(Dl(ul(a.a,new yl)))}
function fw(a){return typeof a===Sxb||typeof a===Zxb}
function Ct(a){$wnd.setTimeout(function(){throw a},0)}
function oI(a,b){return a>0?new tI(a-1,b):new tI(a,b)}
function Ib(a){_b(a);return aw(a,345)?Wv(a,345):xb(a)}
function Rwb(a,b){return bwb(a.a,b,(xkb(),vkb))==null}
function Po(a,b){var c;c=a.a.Y();$b(b,c);return c-1-b}
function hu(a,b,c){var d;d=gu(a,b);iu(a,b,c);return d}
function Nkb(a,b,c){var d;d=Mkb(a,b);$kb(c,d);return d}
function Mkb(a,b){var c;c=new Kkb;c.i=a;c.d=b;return c}
function Mk(a,b,c){this.a=a;bc(c,b);this.c=b;this.b=c}
function Av(a,b,c){zxb(c==null||sv(a,c));return a[b]=c}
function Pm(a){a.a=null;a.e=null;Ymb(a.b);a.d=0;++a.c}
function Pmb(a){slb.call(this,(bmb(),a==null?Wxb:a))}
function Omb(a){slb.call(this,(bmb(),a==null?Wxb:a))}
function Om(a){var b;return b=a.f,!b?(a.f=new Pp(a)):b}
function Jd(a){var b;return b=a.k,!b?(a.k=new Qg(a)):b}
function Be(a){var b;b=a.e;return !b?(a.e=new Fp(a)):b}
function Vg(a){var b;b=a.e;!b&&(a.e=b=a.gb());return b}
function d6(a){var b,c;b=a.c.f.d;c=a.d.f.d;return b==c}
function Gfb(a,b){var c;c=new Dfb(a);Afb(c,b);return c}
function umb(a,b){a.a+=String.fromCharCode(b);return a}
function hX(a){if(!a.a&&!!a.d){return a.d.b}return a.a}
function _H(a){if(UH(a)){return a|0}return a.l|a.m<<22}
function xo(a){Mh(a,Uyb);return $s(PH(PH(5,a),a/10|0))}
function Smb(a,b){return ew(b)?Tmb(a,b):re(Ktb(a.d,b))}
function tl(a){return aw(a,19)?Wv(a,19).Y():Ul(a.mb())}
function pr(a){return a?new xtb((Oh(),a)):qr(null.mb())}
function Tb(a,b){return gw(a)===gw(b)||a!=null&&rb(a,b)}
function zT(a,b){return vT(),glb(Ixb(Yv(a)),Ixb(Yv(b)))}
function Ep(a){return mp(),Wl(a.a.bb().mb(),(xp(),wp))}
function Gi(){Gi=iI;hi();Fi=new gr((ypb(),ypb(),vpb))}
function kr(){kr=iI;hi();jr=new lr((ypb(),ypb(),xpb))}
function Exb(a,b){if(a==null){throw new Wlb((bmb(),b))}}
function Zfb(a,b){Mfb();return (a-b<=0?0-(a-b):a-b)<0.2}
function U0(a,b){return a.i.b<b.i.b?-1:a.i.b==b.i.b?0:1}
function Zjb(a,b,c,d){a.g[b.e][c.e]=d;a.g[c.e][b.e]=d}
function vnb(a){uxb(a.c!=-1);a.d.vb(a.c);a.b=a.c;a.c=-1}
function Sub(a){this.c=a;this.b=a.a.b.a;lsb(a.a.c,this)}
function ufb(a){efb.call(this,new opb(a));this.a=new FI}
function er(){Bk.call(this,new ir(new ntb));this.a=this}
function OQ(){JQ();this.b=(mp(),new ntb);this.a=new ntb}
function zp(){xp();return Bv(tv(jy,1),uyb,188,0,[vp,wp])}
function Ih(){Gh();return Bv(tv(dx,1),uyb,159,0,[Fh,Eh])}
function ss(){qs();return Bv(tv(Ty,1),uyb,205,0,[ps,os])}
function psb(a){We(a.a);a.b=xv(UF,syb,1,a.b.length,4,1)}
function krb(a){!a.b&&(a.b=new Frb(a.c.W()));return a.b}
function cwb(a,b){var c;c=new zwb;ewb(a,b,c);return c.d}
function Qkb(a,b){var c;c=Mkb('',a);c.k=b;c.g=1;return c}
function We(a){var b;for(b=a.mb();b.G();){b.H();b.I()}}
function yJ(a,b){return aw(b,79)&&emb(a.b,Wv(b,79).mc())}
function Z3(){X3();return Bv(tv(iD,1),uyb,175,0,[V3,W3])}
function a8(){Z7();return Bv(tv(WD,1),uyb,193,0,[X7,Y7])}
function s9(){p9();return Bv(tv(hE,1),uyb,192,0,[o9,n9])}
function Umb(a,b,c){return ew(b)?Vmb(a,b,c):Ltb(a.d,b,c)}
function h5(a,b,c){a.i=0;a.e=0;if(b==c){return}d5(a,b,c)}
function g5(a,b,c){a.i=0;a.e=0;if(b==c){return}c5(a,b,c)}
function t6(a,b,c,d){this.d=a;this.b=b;this.a=c;this.c=d}
function VN(a,b,c,d){this.d=a;this.e=b;this.c=c;this.b=d}
function E5(a,b,c,d){this.a=a;this.c=b;this.b=c;this.d=d}
function vO(a,b,c,d){Ac.call(this,a,b);this.a=c;this.b=d}
function Jtb(a,b){var c;c=Ttb(a.a,b);return c==null?[]:c}
function kmb(a,b){bmb();if(a==b){return 0}return a<b?-1:1}
function CR(a,b){var c;c=hR(a.f,b);return vI(zI(c),a.f.d)}
function qsb(a,b){return Ysb(a.a,b)?a.b[Wv(b,17).e]:null}
function ovb(a,b){return gw(a)===gw(b)||a!=null&&rb(a,b)}
function Pu(a,b){if(b==null){throw new Vlb}return Qu(a,b)}
function Zv(a){Hxb(a==null||fw(a)&&!(a.ad===kI));return a}
function irb(a){!a.a&&(a.a=new Nrb(a.c.bb()));return a.a}
function lrb(a){!a.d&&(a.d=new zqb(a.c.fb()));return a.d}
function _I(a){a.a.a=a.c;a.c.b=a.a;a.a.b=a.c.a=null;a.b=0}
function Cnb(a){return Bxb(a.b<a.d.Y()),a.d.sb(a.c=a.b++)}
function Xmb(a,b){return b==null?Mtb(a.d,null):eub(a.e,b)}
function $9(a,b){this.g=a;this.d=Bv(tv(qB,1),Nzb,9,0,[b])}
function KS(a){this.c=a;this.b=new Wwb(Wv(_b(new MS),56))}
function hW(){this.a=new jJ;this.b=(Mh(3,Vyb),new HU(3))}
function Dg(a,b){this.a=a;yg.call(this,a,Wv(a.d,20).ub(b))}
function rab(a,b,c,d){this.a=a;this.c=b;this.b=c;this.d=d}
function Zlb(a,b,c){this.a=Yxb;this.d=a;this.b=b;this.c=c}
function $W(){XW(this);this.d=0;this.b=0;this.a=0;this.c=0}
function Bcb(){this.b=new vtb;this.d=new aJ;this.e=new Uvb}
function ypb(){ypb=iI;vpb=new Kpb;wpb=new aqb;xpb=new iqb}
function Lc(){Lc=iI;Ic=new Oc;Hc=new Rc;Jc=new Uc;Kc=new Xc}
function Z7(){Z7=iI;X7=new $7('GREEDY',0);Y7=new $7(zAb,1)}
function zQ(){zQ=iI;yQ=new AJ((eM(),EL),(xkb(),xkb(),wkb))}
function w9(){w9=iI;v9=PQ(UQ(TQ(new WQ,(d0(),N_)),B_),M_)}
function N6(a,b){var c;c=M6(b);return Wv(Smb(a.c,c),24).a}
function PR(a,b){var c;c=utb(a.a,b);c&&(b.f=null);return c}
function Krb(a){var b;b=a.b.ob();Mrb(b,b.length);return b}
function NP(a){if(a<0){return -1}if(a>0){return 1}return 0}
function mP(){kP();return Bv(tv(Rz,1),uyb,171,0,[jP,gP,hP])}
function gL(){eL();return Bv(tv(Fz,1),uyb,166,0,[cL,bL,dL])}
function WM(){UM();return Bv(tv(Jz,1),uyb,149,0,[TM,SM,RM])}
function FO(){DO();return Bv(tv(Pz,1),uyb,225,0,[BO,AO,CO])}
function ZZ(){XZ();return Bv(tv(VB,1),uyb,221,0,[VZ,WZ,UZ])}
function A8(){x8();return Bv(tv(_D,1),uyb,173,0,[w8,v8,u8])}
function QH(a,b){return SH(Hv(UH(a)?YH(a):a,UH(b)?YH(b):b))}
function XI(a){return a.b==0?null:(Bxb(a.b!=0),$I(a,a.a.a))}
function zfb(a){a.d=a.d-15;a.b=a.b-15;a.c=a.c+15;a.a=a.a+15}
function Rn(a){this.b=a;this.c=a;a.e=null;a.c=null;this.a=1}
function nZ(a,b,c){this.d=a;this.b=new GU;this.c=b;this.a=c}
function sfb(a,b){qfb(this,new HI(a.a,a.b));rfb(this,Eo(b))}
function Xf(a,b){if(b===a){return true}Yf(a);return a.d.t(b)}
function Oeb(a){if(a==neb||a==keb){return true}return false}
function VO(a){if(!Qob(new Tob(zW(a.e)))){return}OO(a);QO(a)}
function Y2(a,b){var c;c=Wv(vub(a.e,b),116);!!c&&(a.d=true)}
function Lrb(a,b){var c;c=a.b.pb(b);Mrb(c,a.b.Y());return c}
function a6(a){var b;b=e6(a,(sN(),rN));b+=e6(a,ZM);return b}
function f6(a,b,c){j6(a,b,c,(sN(),ZM),a.f);j6(a,b,c,rN,a.n)}
function PX(a,b){!!a.f&&BU(a.f.f,a);a.f=b;!!a.f&&vU(a.f.f,a)}
function rX(a,b){!!a.d&&BU(a.d.a,a);a.d=b;!!a.d&&vU(a.d.a,a)}
function eW(a,b){!!a.d&&BU(a.d.b,a);a.d=b;!!a.d&&vU(a.d.b,a)}
function dW(a,b){!!a.c&&BU(a.c.e,a);a.c=b;!!a.c&&vU(a.c.e,a)}
function Zdb(a){var b;b=Eo(a.b);Ue(b,a.c);Ue(b,a.i);return b}
function Qxb(){if(Lxb==256){Kxb=Mxb;Mxb={};Lxb=0}++Lxb}
function Gbb(){Gbb=iI;Fbb=new Hbb(pzb,0);Ebb=new Hbb(ozb,1)}
function fgb(){fgb=iI;dgb=new ggb(ozb,0);egb=new ggb(pzb,1)}
function hgb(){fgb();return Bv(tv(fF,1),uyb,223,0,[dgb,egb])}
function xab(){vab();return Bv(tv(rE,1),uyb,242,0,[uab,tab])}
function Ibb(){Gbb();return Bv(tv(BE,1),uyb,248,0,[Fbb,Ebb])}
function Nbb(){Lbb();return Bv(tv(CE,1),uyb,247,0,[Jbb,Kbb])}
function ncb(){lcb();return Bv(tv(JE,1),uyb,194,0,[jcb,kcb])}
function Ohb(){Mhb();return Bv(tv(pF,1),uyb,174,0,[Khb,Lhb])}
function Hpb(a){ypb();return aw(a,63)?new csb(a):new Rqb(a)}
function Rm(a){var b;return b=a.g,Wv(!b?(a.g=new En(a)):b,20)}
function Ktb(a,b){return Itb(a,b,Jtb(a,b==null?0:a.b.Vc(b)))}
function tX(a){var b;return b=lX(a),'n_'+(b==null?Dlb(a.k):b)}
function ob(a){return Ikb(tb(a))+'@'+(vb(a)>>>0).toString(16)}
function ykb(a,b){return zkb(Ckb((Dxb(a),a)),Ckb((Dxb(b),b)))}
function Tmb(a,b){return b==null?re(Ktb(a.d,null)):cub(a.e,b)}
function Rr(a,b,c){return new Ur(a.c,pk(a.b,wk(a.d,b,c)),a.a)}
function hw(a){return Math.max(Math.min(a,$xb),-2147483648)|0}
function Ptb(a){this.e=a;this.b=this.e.a.entries();this.a=[]}
function xf(a){this.c=a;this.b=new rnb((new inb(this.c.a)).a)}
function Em(a){this.b=(Il(),Il(),Il(),Gl);this.a=Wv(_b(a),35)}
function EJ(a,b,c){wJ();DJ.call(this,a,b);c!=null&&(this.c=c)}
function cc(a,b,c){if(a<0||b<a||b>c){throw new okb(Wb(a,b,c))}}
function $b(a,b){if(a<0||a>=b){throw new okb(Ub(a,b))}return a}
function ac(a,b){if(a==null){throw new Wlb((bmb(),b))}return a}
function Dm(a){if(!Cm(a)){throw new nvb}a.c=a.b;return a.b.H()}
function jI(a){function b(){}
;b.prototype=a||{};return new b}
function rr(a){var b;b=new wtb(op(a.length));zpb(b,a);return b}
function Gub(a){var b;b=a.c.b.b;a.b=b;a.a=a.c.b;b.a=a.c.b.b=a}
function jwb(a){this.b=null;!a&&(a=(hsb(),hsb(),gsb));this.a=a}
function W6(a){this.b=a;this.a=new Fnb(this.b,this.b.c.length)}
function Li(a){Gi();_b(a);return a?Ki(a):Ki(Bo(new Tob(null)))}
function rt(a,b){var c=qt[a.charCodeAt(0)];return c==null?a:c}
function Skb(a,b){var c=a.a=a.a||[];return c[b]||(c[b]=a.Oc(b))}
function CU(a,b,c){var d;Gxb(b,c,a.c.length);d=c-b;hxb(a.c,b,d)}
function Ur(a,b,c){Ch.call(this,b.a);this.c=a;this.b=b;this.a=c}
function ko(a){Vm(a.c);a.e=a.a=a.c;a.c=a.c.c;++a.d;return a.a.f}
function lo(a){Vm(a.e);a.c=a.a=a.e;a.e=a.e.e;--a.d;return a.a.f}
function MX(a){return MI(Bv(tv(qz,1),Fzb,10,0,[a.f.i,a.i,a.a]))}
function GK(){EK();return Bv(tv(Cz,1),uyb,107,0,[DK,AK,BK,CK])}
function PK(){NK();return Bv(tv(Dz,1),uyb,122,0,[MK,KK,JK,LK])}
function ON(){MN();return Bv(tv(Mz,1),uyb,139,0,[KN,LN,JN,IN])}
function FN(){DN();return Bv(tv(Lz,1),uyb,150,0,[BN,CN,AN,zN])}
function Nc(){Lc();return Bv(tv(Bw,1),uyb,136,0,[Ic,Hc,Jc,Kc])}
function iT(){cT();return Bv(tv(yA,1),uyb,201,0,[$S,bT,_S,aT])}
function wN(){sN();return Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN])}
function xK(){sK();return Bv(tv(Bz,1),uyb,59,0,[qK,pK,oK,nK,rK])}
function c8(){c8=iI;b8=Cc((Z7(),Bv(tv(WD,1),uyb,193,0,[X7,Y7])))}
function _3(){_3=iI;$3=Cc((X3(),Bv(tv(iD,1),uyb,175,0,[V3,W3])))}
function u9(){u9=iI;t9=Cc((p9(),Bv(tv(hE,1),uyb,192,0,[o9,n9])))}
function Jhb(){Hhb();return Bv(tv(oF,1),uyb,140,0,[Fhb,Ghb,Ehb])}
function Jgb(){Hgb();return Bv(tv(jF,1),uyb,218,0,[Fgb,Egb,Ggb])}
function fjb(){djb();return Bv(tv(rF,1),uyb,219,0,[cjb,ajb,bjb])}
function Sjb(){Qjb();return Bv(tv(sF,1),uyb,153,0,[Njb,Pjb,Ojb])}
function ekb(){ckb();return Bv(tv(uF,1),uyb,172,0,[_jb,akb,bkb])}
function Vmb(a,b,c){return b==null?Ltb(a.d,null,c):dub(a.e,b,c)}
function wk(a,b,c){return new sk(a,false,null,(Gh(),Fh),true,b,c)}
function tsb(a,b){return $sb(a.a,b)?usb(a,Wv(b,17).e,null):null}
function ql(a){_b(a);return Ql((Il(),new Im(Dl(ul(a.a,new yl)))))}
function Epb(a){ypb();if(!a){return nqb(),mqb}return new Ipb(a)}
function Oo(a,b){var c,d;d=Qo(a,b);c=a.a.ub(d);return new bp(a,c)}
function Cpb(a,b){var c,d;d=a.Y();for(c=0;c<d;c++){a.wb(c,b[c])}}
function Xbb(a,b,c){var d;d=new Wbb;d.b=b;d.a=c;++b.b;vU(a.d,d)}
function fW(a,b,c){!!a.d&&BU(a.d.b,a);a.d=b;!!a.d&&uU(a.d.b,c,a)}
function Mnb(a,b,c){Gxb(b,c,a.Y());this.c=a;this.a=b;this.b=c-b}
function vP(a,b,c,d){sP(this);this.d=a;this.b=b;this.a=c;this.c=d}
function zr(a,b){Bk.call(this,Fpb(_b(a),_b(b)));this.b=a;this.c=b}
function Fnb(a,b){this.a=a;wnb.call(this,a);Fxb(b,a.Y());this.b=b}
function FJ(a,b,c,d){wJ();EJ.call(this,a,b,c);d!=null&&(this.d=d)}
function e5(a,b,c){a.i=0;a.e=0;if(b==c){return}d5(a,b,c);c5(a,b,c)}
function Rob(a){Bxb(a.a<a.c.c.length);a.b=a.a++;return a.c.c[a.b]}
function avb(a){Bxb(a.b.b!=a.d.a);a.c=a.b=a.b.b;--a.a;return a.c.c}
function gwb(a,b){var c;c=1-b;a.a[c]=hwb(a.a[c],c);return hwb(a,b)}
function S2(a){var b;b=(Ieb(),Ieb(),heb);a.d&&Z2(a);ni();return b}
function ZH(a){var b;if(UH(a)){b=a;return b==-0.?0:b}return Nv(a)}
function Ii(a){var b;b=(_b(a),new IU((Oh(),a)));Dpb(b);return Yi(b)}
function Rl(a){Il();var b;while(true){b=a.H();if(!a.G()){return b}}}
function Yn(a){Xn(a);Vm(a.c);a.e=a.a=a.c;a.c=a.c.b;++a.d;return a.a}
function Zn(a){Xn(a);Vm(a.e);a.c=a.a=a.e;a.e=a.e.d;--a.d;return a.a}
function Wf(a){var b;b=a.Y();if(b==0){return}a.d.Q();a.f.c-=b;$f(a)}
function At(a,b,c){var d;d=yt();try{return xt(a,b,c)}finally{Bt(d)}}
function zt(b){return function(){return At(b,this,arguments);// removed by dead control flow
{ var a; }}}
function sl(a){if(aw(a,19)){return Wv(a,19).V()}return !a.mb().G()}
function gr(a){Gi();this.a=(ypb(),aw(a,63)?new csb(a):new Rqb(a))}
function Mhb(){Mhb=iI;Khb=new Nhb(qzb,0);Lhb=new Nhb('TOP_LEFT',1)}
function Lbb(){Lbb=iI;Jbb=new Mbb('DOWN',0);Kbb=new Mbb('UP',1)}
function p9(){p9=iI;o9=new q9('LAYER_SWEEP',0);n9=new q9(zAb,1)}
function vab(){vab=iI;uab=new wab('UPPER',0);tab=new wab('LOWER',1)}
function yxb(a){if(a<0){throw new Ulb('Negative array size: '+a)}}
function hnb(a,b){if(aw(b,21)){return ee(a.a,Wv(b,21))}return false}
function Esb(a,b){if(aw(b,21)){return ee(a.a,Wv(b,21))}return false}
function Kub(a,b){if(aw(b,21)){return ee(a.a,Wv(b,21))}return false}
function IV(a){var b;b=new hW;qJ(b,a);sJ(b,(eM(),CL),null);return b}
function je(a,b){return b===a?'(this Map)':(bmb(),b==null?Wxb:xb(b))}
function Ld(a,b,c,d){return aw(c,63)?new ug(a,b,c,d):new mg(a,b,c,d)}
function BM(){zM();return Bv(tv(Hz,1),uyb,100,0,[yM,xM,uM,vM,wM])}
function OM(){KM();return Bv(tv(Iz,1),uyb,28,0,[JM,IM,HM,EM,GM,FM])}
function kK(){iK();return Bv(tv(Az,1),uyb,103,0,[cK,fK,gK,hK,dK,eK])}
function $K(){YK();return Bv(tv(Ez,1),uyb,133,0,[WK,UK,XK,SK,VK,TK])}
function YM(){YM=iI;XM=Cc((UM(),Bv(tv(Jz,1),uyb,149,0,[TM,SM,RM])))}
function iL(){iL=iI;hL=Cc((eL(),Bv(tv(Fz,1),uyb,166,0,[cL,bL,dL])))}
function C8(){C8=iI;B8=Cc((x8(),Bv(tv(_D,1),uyb,173,0,[w8,v8,u8])))}
function EX(){CX();return Bv(tv(pB,1),uyb,132,0,[AX,zX,xX,BX,yX,wX])}
function i4(){g4();return Bv(tv(jD,1),uyb,125,0,[e4,b4,f4,d4,c4,a4])}
function Vl(a){Il();return umb(Gb((Oh(),Nh),umb(new zmb,91),a),93).a}
function Gpb(a,b){ypb();var c;c=a.ob();ipb(c,0,c.length,b);Cpb(a,c)}
function G3(a,b,c,d,e){this.c=a;this.e=b;this.d=c;this.b=d;this.a=e}
function Peb(a,b,c,d,e){Ac.call(this,a,b);this.a=c;this.b=d;this.c=e}
function Ahb(a,b,c,d,e){Ac.call(this,a,b);this.a=c;this.b=d;this.c=e}
function QT(a,b,c){this.a=b;this.c=a;this.b=(_b(c),new IU((Oh(),c)))}
function $U(){tU(this);this.b=new HI(Uzb,Uzb);this.a=new HI(Vzb,Vzb)}
function X3(){X3=iI;V3=new Y3('QUADRATIC',0);W3=new Y3('SCANLINE',1)}
function Te(){throw new Imb('Add not supported on this collection')}
function pq(a){var b,c;c=qmb(a.Zb());b=a.Yb();return b==1?c:c+' x '+b}
function _ub(a){Bxb(a.b!=a.d.c);a.c=a.b;a.b=a.b.a;++a.a;return a.c.c}
function Ukb(a){if(a.Tc()){return null}var b=a.k;var c=fI[b];return c}
function bc(a,b){if(a<0||a>b){throw new okb(Vb(a,b,'index'))}return a}
function Zf(a,b){var c;Yf(a);c=a.d.nb(b);if(c){--a.f.c;$f(a)}return c}
function RT(a,b,c){var d;d=(_b(a),new IU((Oh(),a)));PT(new QT(d,b,c))}
function cmb(a,b){return kmb((bmb(),a.toLowerCase()),b.toLowerCase())}
function rmb(a,b){return kmb((bmb(),a.toLowerCase()),b.toLowerCase())}
function Jwb(){Fwb();return Bv(tv(DH,1),uyb,138,0,[Bwb,Cwb,Dwb,Ewb])}
function bxb(a,b,c,d){Array.prototype.splice.apply(a,[b,c].concat(d))}
function TI(a,b,c,d){var e;e=new mvb;e.c=b;e.b=c;e.a=d;d.b=c.a=e;++a.b}
function Sm(a,b){var c;c=Hpb(Bo(new mo(a,b)));Ml(new mo(a,b));return c}
function Su(d,a,b){if(b){var c=b.gc();d.a[a]=c(b)}else{delete d.a[a]}}
function iu(d,a,b){if(b){var c=b.gc();b=c(b)}else{b=undefined}d.a[a]=b}
function Dfb(a){yfb(this);this.d=a.d;this.c=a.c;this.a=a.a;this.b=a.b}
function n7(){this.g=new q7;this.c=new q7;this.a=new GU;this.k=new GU}
function dR(){this.d=new OQ;this.a=new tV;this.c=new SV;this.b=new CV}
function oR(){this.i=new GU;this.g=new FI;this.n=new xS;this.q=new xS}
function _Y(a,b,c,d){this.e=a;this.b=new GU;this.d=b;this.a=c;this.c=d}
function oT(){oT=iI;lT=new FT;mT=new HT;jT=new JT;kT=new LT;nT=new NT}
function DO(){DO=iI;BO=new EO(ozb,0);AO=new EO(qzb,1);CO=new EO(pzb,2)}
function IK(){IK=iI;HK=Cc((EK(),Bv(tv(Cz,1),uyb,107,0,[DK,AK,BK,CK])))}
function RK(){RK=iI;QK=Cc((NK(),Bv(tv(Dz,1),uyb,122,0,[MK,KK,JK,LK])))}
function QN(){QN=iI;PN=Cc((MN(),Bv(tv(Mz,1),uyb,139,0,[KN,LN,JN,IN])))}
function HN(){HN=iI;GN=Cc((DN(),Bv(tv(Lz,1),uyb,150,0,[BN,CN,AN,zN])))}
function pcb(){pcb=iI;ocb=Cc((lcb(),Bv(tv(JE,1),uyb,194,0,[jcb,kcb])))}
function Qhb(){Qhb=iI;Phb=Cc((Mhb(),Bv(tv(pF,1),uyb,174,0,[Khb,Lhb])))}
function Ao(a){_b(a);return aw(a,19)?new IU((Oh(),Wv(a,19))):Bo(a.mb())}
function yY(a){return Ckb(Ixb(Xv(rJ(a,(Rib(),Vhb)))))&&rJ(a,uib)!=null}
function UY(a){return Ckb(Ixb(Xv(rJ(a,(Rib(),Vhb)))))&&rJ(a,uib)!=null}
function jkb(a,b,c,d){b==null&&(b=Wxb);a.a+=''+(bmb(),b.substr(c,d-c))}
function Mrb(a,b){var c;for(c=0;c<b;++c){Av(a,c,new Xrb(Wv(a[c],21)))}}
function Hd(a,b){var c,d;c=Wv(sp(a.b,b),19);if(c){d=c.Y();c.Q();a.c-=d}}
function DU(a,b,c){var d;d=(Cxb(b,a.c.length),a.c[b]);a.c[b]=c;return d}
function itb(a){Bxb(a.a<a.c.a.length);a.b=a.a;gtb(a);return a.c.b[a.b]}
function Ul(a){Il();var b;b=0;while(a.G()){a.H();b=PH(b,1)}return $s(b)}
function hub(a){this.d=a;this.b=this.d.a.entries();this.a=this.b.next()}
function DT(a){this.g=a;this.f=new GU;this.a=Qlb(this.g.c.c,this.g.d.c)}
function kt(a){it();this.e=null;this.f=null;this.a='';this.b=a;this.a=''}
function wub(){ntb.call(this);pub(this);this.b.b=this.b;this.b.a=this.b}
function Bt(a){a&&It((Gt(),Ft));--ut;if(a){if(wt!=-1){Dt(wt);wt=-1}}}
function bW(a){if(!a.c||!a.d){return false}return !!a.c.f&&a.c.f==a.d.f}
function pt(){if(Date.now){return Date.now()}return (new Date).getTime()}
function lX(a){if(a.c.c.length!=0){return Wv(yU(a.c,0),33).a}return null}
function OX(a){if(a.c.c.length!=0){return Wv(yU(a.c,0),33).a}return null}
function qd(a){a.d=3;a.c=sm(a);if(a.d!=2){a.d=0;return true}return false}
function bgb(a,b,c){this.a=a;this.b=b;this.c=c;vU(a.j,this);vU(b.d,this)}
function VP(a,b,c,d){var e;a.c?(e=new Gu(hw(d))):(e=new Gu(d));Ru(b,c,e)}
function Co(a){var b,c;_b(a);b=xo(a.length);c=new HU(b);zpb(c,a);return c}
function Dv(a){var b,c,d;b=a&azb;c=a>>22&azb;d=a<0?bzb:0;return Ev(b,c,d)}
function nbb(){kbb();return Bv(tv(zE,1),uyb,141,0,[jbb,gbb,hbb,fbb,ibb])}
function Sgb(){Pgb();return Bv(tv(kF,1),uyb,115,0,[Lgb,Kgb,Ngb,Mgb,Ogb])}
function Zib(){Xib();return Bv(tv(qF,1),uyb,85,0,[Wib,Sib,Tib,Uib,Vib])}
function zK(){zK=iI;yK=Cc((sK(),Bv(tv(Bz,1),uyb,59,0,[qK,pK,oK,nK,rK])))}
function yN(){yN=iI;xN=Cc((sN(),Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN])))}
function DM(){DM=iI;CM=Cc((zM(),Bv(tv(Hz,1),uyb,100,0,[yM,xM,uM,vM,wM])))}
function F9(){F9=iI;E9=PQ(UQ(UQ(UQ(TQ(new WQ,(d0(),N_)),U_),r_),B_),M_)}
function TT(a,b){var c,d;for(d=b.mb();d.G();){c=Wv(d.H(),55);ST(a,c,0,0)}}
function VT(a,b,c){var d,e;for(e=a.mb();e.G();){d=Wv(e.H(),55);UT(d,b,c)}}
function X8(a,b,c){var d,e;d=0;for(e=0;e<b.length;e++){d+=a.Hc(b[e],d,c)}}
function AU(a,b){var c;c=(Cxb(b,a.c.length),a.c[b]);hxb(a.c,b,1);return c}
function Kl(a){var b;_b(a);Yb(true);for(b=0;b<0&&Cm(a);b++){Dm(a)}return b}
function Ymb(a){var b;a.d=new Ntb(a);a.e=new fub(a);b=a[WAb]|0;a[WAb]=b+1}
function igb(a){a.g=new vtb;a.o=new vtb;a.c=new vtb;a.j=new GU;a.d=new GU}
function Fxb(a,b){if(a<0||a>b){throw new okb('Index: '+a+', Size: '+b)}}
function Cxb(a,b){if(a<0||a>=b){throw new okb('Index: '+a+', Size: '+b)}}
function uob(a,b){var c,d;c=b.yb();d=Wvb(a,c);return !!d&&ovb(d.e,b.zb())}
function zbb(a,b){var c;c=a.d;if(b>0){return Wv(yU(c.a,b-1),9)}return null}
function xv(a,b,c,d,e,f){var g;g=yv(e,d);e!=9&&Bv(tv(a,f),b,c,e,g);return g}
function pd(a){var b;if(!od(a)){throw new nvb}a.d=1;b=a.c;a.c=null;return b}
function _f(a,b,c,d){this.f=a;this.e=b;this.d=c;this.b=d;this.c=!d?null:d.d}
function MH(b,c){if(b&&typeof b==Sxb){try{b.__gwt$exception=c}catch(a){}}}
function wT(a,b){if(a.a.$b(b.d,a.b)>0){vU(a.c,new WS(b.c,b.d,a.d));a.b=b.d}}
function W4(a,b){var c;c=glb(a.j,b.j);if(c==0){return glb(a.k,b.k)}return c}
function C6(a){var b,c;c=Wv(yU(a.f,0),7);b=Wv(rJ(c,(Rib(),uib)),7);return b}
function M6(a){var b,c;c=Wv(yU(a.f,0),7);b=Wv(rJ(c,(Rib(),uib)),7);return b}
function B$(a,b){return glb(Ixb(Yv(rJ(a,(Rib(),Cib)))),Ixb(Yv(rJ(b,Cib))))}
function Ujb(){Ujb=iI;Tjb=Cc((Qjb(),Bv(tv(sF,1),uyb,153,0,[Njb,Pjb,Ojb])))}
function gkb(){gkb=iI;fkb=Cc((ckb(),Bv(tv(uF,1),uyb,172,0,[_jb,akb,bkb])))}
function mK(){mK=iI;lK=Cc((iK(),Bv(tv(Az,1),uyb,103,0,[cK,fK,gK,hK,dK,eK])))}
function aL(){aL=iI;_K=Cc((YK(),Bv(tv(Ez,1),uyb,133,0,[WK,UK,XK,SK,VK,TK])))}
function QM(){QM=iI;PM=Cc((KM(),Bv(tv(Iz,1),uyb,28,0,[JM,IM,HM,EM,GM,FM])))}
function k4(){k4=iI;j4=Cc((g4(),Bv(tv(jD,1),uyb,125,0,[e4,b4,f4,d4,c4,a4])))}
function K1(){I1();return Bv(tv(GC,1),uyb,109,0,[G1,B1,E1,C1,D1,A1,F1,H1])}
function qM(){oM();return Bv(tv(Gz,1),uyb,41,0,[gM,fM,iM,nM,mM,lM,jM,kM,hM])}
function Bgb(){zgb();return Bv(tv(iF,1),uyb,123,0,[ygb,xgb,wgb,ugb,tgb,vgb])}
function bhb(){_gb();return Bv(tv(lF,1),uyb,124,0,[Ygb,Xgb,$gb,Wgb,Zgb,Vgb])}
function bK(){bK=iI;aK=new DJ('de.cau.cs.kieler.labels.labelManager',null)}
function ixb(){if(Date.now){return Date.now()}return (new Date).getTime()}
function Xsb(a){var b;b=Wv(cxb(a.b,a.b.length),11);return new atb(a.a,b,a.c)}
function dmb(a,b){var c;c=(bmb(),b.length);return emb(imb(a,a.length-c,c),b)}
function dwb(a,b){var c;c=new zwb;c.c=true;c.d=b.zb();return ewb(a,b.yb(),c)}
function He(a,b){var c;c=b.yb();return mp(),new Fk(c,Kd(a.b,c,Wv(b.zb(),19)))}
function BU(a,b){var c;c=zU(a,b,0);if(c==-1){return false}a.vb(c);return true}
function Cv(a,b){uv(b)!=9&&Bv(tb(b),b._c,b.__elementTypeId$,uv(b),a);return a}
function Rub(a){ksb(a.c.a.c,a);Bxb(a.b!=a.c.a.b);a.a=a.b;a.b=a.b.a;return a.a}
function qnb(a){uxb(!!a.c);ksb(a.e,a);a.c.I();a.c=null;a.b=onb(a);lsb(a.e,a)}
function Acb(a,b,c){a.a=b;a.c=c;a.b.a.Q();_I(a.d);a.e.a.c=xv(UF,syb,1,0,4,1)}
function Ar(a,b,c){Bk.call(this,Fpb(_b(a),_b(b)));this.b=a;this.c=b;this.a=c}
function j9(a,b,c,d){this.b=new l9(this);this.a=a;this.c=b;this.e=c;this.d=d}
function xub(a){$mb.call(this,a,0);pub(this);this.b.b=this.b;this.b.a=this.b}
function ywb(a,b){qob.call(this,a,b);this.a=xv(yH,syb,183,2,0,1);this.b=true}
function Qmb(a,b){return ew(b)?b==null?!!Ktb(a.d,null):bub(a.e,b):!!Ktb(a.d,b)}
function RR(a,b){return Ws(),(a-b>0?a-b:-(a-b))<=$yb||a==b||isNaN(a)&&isNaN(b)}
function Xs(a,b){Ws();return (a-b>0?a-b:-(a-b))<=$yb||a==b||isNaN(a)&&isNaN(b)}
function Z5(a){var b,c;b=true;do{b?(c=W5(a)):(c=U5(a));b=!b}while(c);S5(a,a.d)}
function Ru(a,b,c){var d;if(b==null){throw new Vlb}d=Pu(a,b);Su(a,b,c);return d}
function sJ(a,b,c){!a.n&&(a.n=new ntb);c==null?Wmb(a.n,b):Umb(a.n,b,c);return a}
function zU(a,b,c){for(;c<a.c.length;++c){if(ovb(b,a.c[c])){return c}}return -1}
function b2(a,b){while(b>=a.a.c.length){vU(a.a,new aJ)}return Wv(yU(a.a,b),20)}
function Fe(a,b){var c;c=Wv(rp(a.a,b),19);if(!c){return null}return Kd(a.b,b,c)}
function XP(a,b,c){var d;d=Pu(a,Gzb);if(!d){d=new Tu;Ru(a,Gzb,d)}Ru(d.kc(),b,c)}
function Okb(a,b,c,d,e){var f;f=Mkb(a,b);$kb(c,f);f.g=e?8:0;f.f=d;f.e=e;return f}
function mo(a,b){var c;this.f=a;this.b=b;c=Wv(Smb(a.b,b),126);this.c=!c?null:c.b}
function fJ(a,b){var c,d,e;for(d=0,e=b.length;d<e;++d){c=b[d];TI(a,c,a.c.b,a.c)}}
function GV(a,b,c,d,e,f){var g;g=IV(d);dW(g,e);eW(g,f);Fd(a.a,d,new XV(g,b,c.f))}
function bab(a,b,c){var d;d=0;a.c[c]>0&&(d+=dab(b));a.b[c]&&(d+=eab(b));return d}
function vub(a,b){var c;c=Wv(Wmb(a.c,b),176);if(c){Hub(c);return c.e}return null}
function $s(a){if(RH(a,$xb)>0){return $xb}if(RH(a,eyb)<0){return eyb}return _H(a)}
function Ph(a){Oh();Mh(a,'size');return _H(VH(WH(a,8),Nyb)?WH(a,8):Nyb),new Amb}
function ukb(a){skb.call(this,(bmb(),a==null?Wxb:xb(a)),aw(a,46)?Wv(a,46):null)}
function HU(a){tU(this);wxb(a>=0,'Initial capacity must not be negative')}
function JQ(){JQ=iI;HQ=VQ(UQ(UQ(new WQ,(d0(),O_)),C_),J_);IQ=TQ(new WQ,G_)}
function LX(){LX=iI;IX=new UX;GX=new XX;HX=new ZX;FX=new _X;JX=new bY;KX=new dY}
function Fwb(){Fwb=iI;Bwb=new Gwb('All',0);Cwb=new Kwb;Dwb=new Mwb;Ewb=new Pwb}
function x8(){x8=iI;w8=new y8(DAb,0);v8=new y8('LONGEST_PATH',1);u8=new y8(zAb,2)}
function Rv(){Rv=iI;Ov=Ev(azb,azb,524287);Pv=Ev(0,0,524288);Dv(1);Dv(2);Qv=Dv(0)}
function M1(){M1=iI;L1=Cc((I1(),Bv(tv(GC,1),uyb,109,0,[G1,B1,E1,C1,D1,A1,F1,H1])))}
function pbb(){pbb=iI;obb=Cc((kbb(),Bv(tv(zE,1),uyb,141,0,[jbb,gbb,hbb,fbb,ibb])))}
function Ugb(){Ugb=iI;Tgb=Cc((Pgb(),Bv(tv(kF,1),uyb,115,0,[Lgb,Kgb,Ngb,Mgb,Ogb])))}
function _ib(){_ib=iI;$ib=Cc((Xib(),Bv(tv(qF,1),uyb,85,0,[Wib,Sib,Tib,Uib,Vib])))}
function zvb(a){tvb();xvb(this,_H(QH(SH(Lv(UH(a)?YH(a):a,24)),bBb)),_H(QH(a,bBb)))}
function tb(a){return ew(a)?$F:cw(a)?HF:bw(a)?EF:_v(a)?a.$c:zv(a)?a.$c:a.$c||$y}
function uv(a){return a.__elementTypeCategory$==null?9:a.__elementTypeCategory$}
function Ht(a){var b,c;if(a.a){c=null;do{b=a.a;a.a=null;c=Lt(b,c)}while(a.a);a.a=c}}
function It(a){var b,c;if(a.b){c=null;do{b=a.b;a.b=null;c=Lt(b,c)}while(a.b);a.b=c}}
function oJ(a){nJ();var b,c;c=jzb;for(b=0;b<a.length;b++){a[b]>c&&(c=a[b])}return c}
function KQ(a,b){var c;c=Wv(Smb(a.b,b),106);if(!c){c=b.rc();Umb(a.b,b,c)}return c}
function rub(a,b){var c;c=Wv(Smb(a.c,b),176);if(c){uub(a,c);return c.e}return null}
function R2(a,b,c,d){var e;e=Wv(rub(a.e,b),116);e.b+=c;e.a+=d;tub(a.e,b,e);a.d=true}
function gtb(a){var b;++a.a;for(b=a.c.a.length;a.a<b;++a.a){if(a.c.b[a.a]){return}}}
function bt(a){var b,c,d;for(b=(a.g==null&&(a.g=Pt(a)),a.g),c=0,d=b.length;c<d;++c);}
function Tf(a,b){var c,d;Yf(a);d=a.d.V();c=a.d.ib(b);if(c){++a.f.c;d&&Vf(a)}return c}
function Mh(a,b){if(a<0){throw new slb(b+' cannot be negative but was: '+a)}return a}
function Yb(a){if(!a){throw new slb((bmb(),'numberToAdvance must be nonnegative'))}}
function nm(a){if(!a.a.G()){a.a=a.b.mb();if(!a.a.G()){throw new nvb}}return a.a.H()}
function Xl(a){Il();var b;_b(a);if(aw(a,108)){b=Wv(a,108);return b}return new km(a)}
function gu(d,a){var b=d.a[a];var c=(ev(),dv)[typeof b];return c?c(b):kv(typeof b)}
function K2(a,b){var c,d;for(d=new Tob(a);d.a<d.c.c.length;){c=Wv(Rob(d),7);J2(c,b)}}
function Z9(a,b){var c,d,e,f;for(d=a.d,e=0,f=d.length;e<f;++e){c=d[e];W9(a.g,c).a=b}}
function hR(a,b){var c;c=EI(xI(Wv(Smb(a.g,b),10)),RN(Wv(Smb(a.f,b),198).b));return c}
function sr(a){var b;return !od(Pl((b=(new Snb(a.b.a)).a.bb().mb(),new Ynb(b)),a.a))}
function bvb(a){var b;uxb(!!a.c);b=a.c.a;$I(a.d,a.c);a.b==a.c?(a.b=b):--a.a;a.c=null}
function gW(a){return !!a.c&&!!a.d?a.c.f+'('+a.c+')->'+a.d.f+'('+a.d+')':'e_'+txb(a)}
function gT(a,b){cT();return a==$S&&b==bT||a==bT&&b==$S||a==aT&&b==_S||a==_S&&b==aT}
function hT(a,b){cT();return a==$S&&b==_S||a==$S&&b==aT||a==bT&&b==aT||a==bT&&b==_S}
function Bhb(){zhb();return Bv(tv(nF,1),uyb,110,0,[shb,whb,thb,xhb,uhb,yhb,vhb,rhb])}
function sM(){sM=iI;rM=Cc((oM(),Bv(tv(Gz,1),uyb,41,0,[gM,fM,iM,nM,mM,lM,jM,kM,hM])))}
function UM(){UM=iI;TM=new VM('OUTSIDE',0);SM=new VM('INSIDE',1);RM=new VM('FIXED',2)}
function Hhb(){Hhb=iI;Fhb=new Ihb(tzb,0);Ghb=new Ihb('TOP',1);Ehb=new Ihb('BOTTOM',2)}
function mxb(){mxb=iI;lxb=new qxb;kxb=new oxb('ISO-LATIN-1');jxb=new oxb('ISO-8859-1')}
function lcb(){lcb=iI;jcb=new mcb('CLASSIC',0);kcb=new mcb('IMPROVE_STRAIGHTNESS',1)}
function kW(){this.e=new FI;this.a=new $W;this.d=new FI;this.b=new GU;this.c=new GU}
function kdb(a,b,c){this.b=b;this.a=a;this.c=c;vU(this.a.e,this);vU(this.b.b,this)}
function Afb(a,b){a.d=Qlb(a.d,b.d);a.c=Nlb(a.c,b.c);a.a=Nlb(a.a,b.a);a.b=Qlb(a.b,b.b)}
function $I(a,b){var c;c=b.c;b.a.b=b.b;b.b.a=b.a;b.a=b.b=null;b.c=null;--a.b;return c}
function Jl(a,b){Il();var c;_b(a);_b(b);c=false;while(b.G()){c=c|a.ib(b.H())}return c}
function pnb(a){var b;ksb(a.e,a);Bxb(a.b);a.c=a.a;b=Wv(a.a.H(),21);a.b=onb(a);return b}
function sm(a){var b;while(a.b.G()){b=a.b.H();if(a.a.D(b)){return b}}return a.d=2,null}
function _sb(a,b){if(!!b&&a.b[b.e]==b){Av(a.b,b.e,null);--a.c;return true}return false}
function TH(a){if(ezb<a&&a<dzb){return a<0?Math.ceil(a):Math.floor(a)}return SH(Jv(a))}
function rl(a){if(a){if(a.V()){throw new nvb}return a.sb(a.Y()-1)}return Rl(null.mb())}
function ybb(a,b){var c;c=a.d;if(b<c.a.c.length-1){return Wv(yU(c.a,b+1),9)}return null}
function $kb(a,b){var c;if(!a){return}b.k=a;var d=Ukb(b);if(!d){fI[a]=[b];return}d.$c=b}
function O5(a,b){var c,d;d=false;do{a.i?(c=V5(a,b)):(c=X5(a,b));d=d|c}while(c);return d}
function Bbb(a,b,c){var d,e;d=b;do{e=Ixb(a.n[d.k])+c;a.n[d.k]=e;d=a.a[d.k]}while(d!=b)}
function M4(a){var b,c;for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);b.vc()}}
function bI(){cI();var a=aI;for(var b=0;b<arguments.length;b++){a.push(arguments[b])}}
function dn(a,b){var c,d;for(c=0,d=a.Y();c<d;++c){if(ovb(b,a.sb(c))){return c}}return -1}
function or(a,b){var c;ac(a,'set1');ac(b,'set2');c=(hc(),new nc(b));return new tr(a,c,b)}
function Rt(a){var b=/function(?:\s+([\w$]+))?\s*\(/;var c=b.exec(a);return c&&c[1]||Xxb}
function YQ(a,b,c){nI(c,Tzb,3);NV(a.c,b,rI(c,1));aR(a,b,rI(c,1));BV(b,rI(c,1));pI(c)}
function Dgb(){Dgb=iI;Cgb=Cc((zgb(),Bv(tv(iF,1),uyb,123,0,[ygb,xgb,wgb,ugb,tgb,vgb])))}
function dhb(){dhb=iI;chb=Cc((_gb(),Bv(tv(lF,1),uyb,124,0,[Ygb,Xgb,$gb,Wgb,Zgb,Vgb])))}
function Ilb(){Ilb=iI;Hlb=Bv(tv(mw,1),Yyb,26,12,[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15])}
function djb(){djb=iI;cjb=new ejb(szb,0);ajb=new ejb('INPUT',1);bjb=new ejb('OUTPUT',2)}
function de(a){this.c=a;this.b=new rnb((new inb(a.b)).a);this.a=null;this.d=(Il(),Il(),Hl)}
function Nn(a){this.e=a;this.d=new wtb(op(ud(this.e).Y()));this.c=this.e.a;this.b=this.e.c}
function qR(a,b,c){this.c=a;oR.call(this);this.b=b;this.j=new VN(b.d,b.e,b.c,b.b);this.a=c}
function qI(a,b){if(a.j>0&&a.c<a.j){a.c+=b;!!a.g&&a.g.d>0&&a.e!=0&&qI(a.g,b/a.j*a.g.d)}}
function WV(a){if(a.b.d.f.g==(CX(),xX)){return Wv(rJ(a.b.d.f,(Rib(),uib)),7)}return a.b.d}
function VV(a){if(a.b.c.f.g==(CX(),xX)){return Wv(rJ(a.b.c.f,(Rib(),uib)),7)}return a.b.c}
function od(a){dc(a.d!=3);switch(a.d){case 2:return false;case 0:return true;}return qd(a)}
function CZ(a){switch(a.e){case 2:return sN(),rN;case 4:return sN(),ZM;default:return a;}}
function DZ(a){switch(a.e){case 1:return sN(),pN;case 3:return sN(),$M;default:return a;}}
function Km(a){var b;if(aw(a,90)){b=Wv(a,90);return new Lm(b.a)}else{return Il(),new dm(a)}}
function Fpb(a,b){ypb();var c;c=new otb(1);ew(a)?Vmb(c,a,b):Ltb(c.d,a,b);return new mrb(c)}
function Is(a,b){if(!a.g){return a.e}else{a.g=Is(a.g,b);--a.a;a.j=XH(a.j,b.c);return Gs(a)}}
function Js(a,b){if(!a.e){return a.g}else{a.e=Js(a.e,b);--a.a;a.j=XH(a.j,b.c);return Gs(a)}}
function Ue(a,b){var c,d,e;Dxb(b);c=false;for(e=b.mb();e.G();){d=e.H();c=c|a.ib(d)}return c}
function nr(a){var b,c,d;b=0;for(d=a.mb();d.G();){c=d.H();b+=c!=null?vb(c):0;b=~~b}return b}
function BY(a){var b,c,d,e;for(c=a.a,d=0,e=c.length;d<e;++d){b=c[d];b.B(null)}return null}
function Xeb(a){var b,c,d;d=new jJ;for(c=a.b.mb();c.G();){b=Wv(c.H(),92);QI(d,b.a)}return d}
function mfb(a){var b,c,d;b=0;for(d=a.mb();d.G();){c=Yv(d.H());b+=(Dxb(c),c)}return b/a.Y()}
function Rbb(a,b){var c;c=Wv(Smb(a.c,b),200);if(!c){c=new Ybb;c.c=b;Umb(a.c,c.c,c)}return c}
function Wsb(a,b){var c;Dxb(b);c=b.e;if(!a.b[c]){Av(a.b,c,b);++a.c;return true}return false}
function hwb(a,b){var c,d;c=1-b;d=a.a[c];a.a[c]=d.a[b];d.a[b]=a;a.b=true;d.b=false;return d}
function yI(a,b){var c;if(aw(b,10)){c=Wv(b,10);return a.a==c.a&&a.b==c.b}else{return false}}
function Bs(a,b,c){a.g=new Os(b,c);es(a,a.g,a.i);a.d=Plb(2,a.d);++a.a;a.j=PH(a.j,c);return a}
function As(a,b,c){a.e=new Os(b,c);es(a.f,a.e,a);a.d=Plb(2,a.d);++a.a;a.j=PH(a.j,c);return a}
function Nu(e,a){var b=e.a;var c=0;for(var d in b){b.hasOwnProperty(d)&&(a[c++]=d)}return a}
function he(a,b){var c,d;Dxb(b);for(d=b.bb().mb();d.G();){c=Wv(d.H(),21);a.db(c.yb(),c.zb())}}
function vcb(a,b,c){var d;d=a.a.e[Wv(b.a,9).k]-a.a.e[Wv(c.a,9).k];return hw(d>0?1:d<0?-1:0)}
function r5(a,b,c){this.g=a;this.d=b;this.e=c;this.a=new GU;p5(this);ypb();Gpb(this.a,null)}
function Os(a,b){Xb(b>0);this.b=a;this.c=b;this.j=b;this.a=1;this.d=1;this.e=null;this.g=null}
function qcb(a){a.a=null;a.e=null;a.b.c=xv(UF,syb,1,0,4,1);a.f.c=xv(UF,syb,1,0,4,1);a.c=null}
function qhb(){ohb();return Bv(tv(mF,1),uyb,113,0,[fhb,hhb,ihb,jhb,khb,lhb,nhb,ehb,ghb,mhb])}
function uvb(a){return wvb(a,26)*1.4901161193847656E-8+wvb(a,27)*1.1102230246251565E-16}
function Fo(a){return aw(a,87)?Ii(Wv(a,87)):aw(a,88)?Wv(a,88).a:aw(a,63)?new ap(a):new Ro(a)}
function Udb(a){var b;b=Wv(rJ(a,(Rib(),hib)),32);return a.g==(CX(),xX)&&(b==(sN(),rN)||b==ZM)}
function YT(a,b){if(ZT(a,b)){Fd(a.a,Wv(rJ(b,(Rib(),fib)),18),b);return true}else{return false}}
function QQ(a,b){var c;if(b){for(c=0;c<6;c++){Wv(yU(a.a,c),18).jb(Wv(yU(b.a,c),19))}}return a}
function rI(a,b){var c;if(a.b){return null}else{c=oI(a.e,a.f);QI(a.a,c);c.g=a;a.d=b;return c}}
function hJ(a,b){var c,d;for(d=WI(a,0);d.b!=d.d.c;){c=Wv(_ub(d),10);c.a+=b.a;c.b+=b.b}return a}
function J9(a,b){var c,d;for(c=0;c<b.length;c++){for(d=0;d<b[c].length;d++){b[c][d]=a[c][d]}}}
function P2(a){var b,c;for(c=new Tob(a.b.f);c.a<c.c.c.length;){b=Wv(Rob(c),7);Y2(a.a,Reb(b.g))}}
function cT(){cT=iI;$S=new fT('Q1',0);bT=new fT('Q4',1);_S=new fT('Q2',2);aT=new fT('Q3',3)}
function EK(){EK=iI;DK=new FK(szb,0);AK=new FK(qzb,1);BK=new FK('HEAD',2);CK=new FK('TAIL',3)}
function ckb(){ckb=iI;_jb=new dkb('AGGRESSIVE',0);akb=new dkb('CAREFUL',1);bkb=new dkb('OFF',2)}
function Dhb(){Dhb=iI;Chb=Cc((zhb(),Bv(tv(nF,1),uyb,110,0,[shb,whb,thb,xhb,uhb,yhb,vhb,rhb])))}
function Akb(a,b){xkb();return ew(a)?kmb(a,$v(b)):cw(a)?flb(a,Yv(b)):bw(a)?ykb(a,Xv(b)):a.F(b)}
function Es(a,b,c){var d;d=b.$b(c,a.b);return d<0?!a.e?0:Es(a.e,b,c):d>0?!a.g?0:Es(a.g,b,c):a.c}
function rk(a,b){var c,d;if(!a.b){return false}d=a.e;c=a.a.$b(b,d);return c<0|c==0&a.d==(Gh(),Fh)}
function qk(a,b){var c,d;if(!a.c){return false}d=a.g;c=a.a.$b(b,d);return c>0|c==0&a.f==(Gh(),Fh)}
function SH(a){var b;b=a.h;if(b==0){return a.l+a.m*czb}if(b==bzb){return a.l+a.m*czb-dzb}return a}
function MI(a){var b,c,d,e;b=new FI;for(d=0,e=a.length;d<e;++d){c=a[d];b.a+=c.a;b.b+=c.b}return b}
function J6(a){var b,c,d,e;for(c=a.a,d=0,e=c.length;d<e;++d){b=c[d];Q6(a,b,(sN(),pN));Q6(a,b,$M)}}
function zo(a){var b,c,d;b=1;for(d=a.mb();d.G();){c=d.H();b=31*b+(c==null?0:vb(c));b=~~b}return b}
function Tsb(a){var b,c;b=Wv(a.e&&a.e(),11);c=Wv(cxb(b,b.length),11);return new atb(b,c,b.length)}
function R6(a){this.e=gw(rJ(hX(a[0]),(eM(),uL)))===gw((NK(),JK));this.a=a;this.c=new ntb;J6(this)}
function kR(a){fR();this.g=(mp(),new ntb);this.f=new ntb;this.b=new ntb;this.c=new xk;this.i=a}
function odb(a){this.o=a;this.g=new GU;this.j=new aJ;this.n=new aJ;this.e=new GU;this.b=new GU}
function OR(a,b){stb(a.a,b);if(b.f){throw new gt('CNode belongs to another CGroup.')}b.f=a}
function eI(a,b){typeof window===Sxb&&typeof window['$gwt']===Sxb&&(window['$gwt'][a]=b)}
function K5(a,b,c,d){var e,f;e=I5(a,b,c,d);e<0&&(e=-e-1);for(f=c-1;f>=e;f--){a[f+1]=a[f]}a[e]=d}
function kab(a,b,c,d){var e,f;e=jab(a,b,c,d);e<0&&(e=-e-1);for(f=c-1;f>=e;f--){a[f+1]=a[f]}a[e]=d}
function Xe(a,b){var c,d;Dxb(b);for(d=b.mb();d.G();){c=d.H();if(!a.kb(c)){return false}}return true}
function Ll(a,b){Il();var c;_b(b);while(a.G()){c=a.H();if(!Udb(Wv(c,9))){return false}}return true}
function wV(a,b){var c,d,e;c=b.k-a.k;if(c==0){d=a.e.a*a.e.b;e=b.e.a*b.e.b;return glb(d,e)}return c}
function YH(a){var b,c,d,e;e=a;d=0;if(e<0){e+=dzb;d=bzb}c=hw(e/czb);b=hw(e-c*czb);return Ev(b,c,d)}
function n6(a,b){a.c.c=xv(UF,syb,1,0,4,1);o6(a,a.e,b);o6(a,a.a,b);ypb();Gpb(a.c,null);return p6(a)}
function c5(a,b,c){a.g=i5(a,b,(sN(),ZM),a.b);a.d=i5(a,c,ZM,a.b);if(a.g.c==0||a.d.c==0){return}f5(a)}
function d5(a,b,c){a.g=i5(a,b,(sN(),rN),a.j);a.d=i5(a,c,rN,a.j);if(a.g.c==0||a.d.c==0){return}f5(a)}
function pU(a,b,c){return new VN(Qlb(a.a,b.a)-c/2,Qlb(a.b,b.b)-c/2,Jlb(a.a-b.a)+c,Jlb(a.b-b.b)+c)}
function onb(a){if(a.a.G()){return true}if(a.a!=a.d){return false}a.a=new Ptb(a.e.d);return a.a.G()}
function xU(a,b){var c,d;c=b.ob();d=c.length;if(d==0){return false}gxb(a.c,a.c.length,c);return true}
function S5(a,b){var c,d;for(c=0;c<a.a.length;c++){for(d=0;d<a.a[c].length;d++){a.a[c][d]=b[c][d]}}}
function zpb(a,b){ypb();var c,d,e,f;f=false;for(d=0,e=b.length;d<e;++d){c=b[d];f=f|a.ib(c)}return f}
function op(a){mp();if(a<3){Mh(a,'expectedSize');return a+1}if(a<Nyb){return hw(a/0.75+1)}return $xb}
function ml(a,b){var c;if(aw(b,19)){c=(Oh(),Wv(b,19));return a.jb(c)}return Jl(a,Wv(_b(b),22).mb())}
function Ufb(a,b){var c,d;d=a.d.f;if(d.g==(CX(),AX)){return}c=Uh(mX(d));Cm(c)&&Umb(b,a,Wv(Dm(c),12))}
function Xob(a,b){var c,d;yxb(b);return c=epb(a,0,b),d=xv(mw,Yyb,26,b,12,1),dxb(a,0,d,0,c,true),d}
function swb(a,b){var c;this.c=a;c=new GU;Zvb(a,c,b,a.b,null,false,null,false);this.a=new Fnb(c,0)}
function is(a){if(!a.a){return false}else if(qk(a.c.b,a.a.b)){a.a=null;return false}else{return true}}
function ec(a){if(!a){throw new ulb((bmb(),'no calls to next() since the last call to remove()'))}}
function ev(){ev=iI;dv={'boolean':fv,'number':gv,'string':iv,'object':hv,'function':hv,'undefined':jv}}
function xR(){xR=iI;vR=rr(Bv(tv(Bz,1),uyb,59,0,[(sK(),oK),pK]));wR=rr(Bv(tv(Bz,1),uyb,59,0,[rK,nK]))}
function Apb(a){ypb();var b,c,d;d=0;for(c=a.mb();c.G();){b=c.H();d=d+(b!=null?vb(b):0);d=d|0}return d}
function Hq(a){Dq();var b,c,d;d=0;for(c=Vg(a).mb();c.G();){b=Wv(c.H(),83);d=PH(d,b.Yb())}return $s(d)}
function dS(a){var b,c;for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);b.i.Q()}a.c.Dc(a);eS(a)}
function eub(a,b){var c;c=Utb(a.a,b);if(c===undefined){++a.d}else{a.a[$Ab](b);--a.c;msb(a.b)}return c}
function X5(a,b){var c,d,e,f;c=false;d=a.d[b].length;for(e=d-1;e>0;e--){f=e-1;c=c|Y5(a,b,f,e)}return c}
function V5(a,b){var c,d,e,f;c=false;d=a.d[b].length;for(f=0;f<d-1;f++){e=f+1;c=c|Y5(a,b,f,e)}return c}
function Gv(a,b){var c,d,e;c=a.l+b.l;d=a.m+b.m+(c>>22);e=a.h+b.h+(d>>22);return Ev(c&azb,d&azb,e&bzb)}
function Mv(a,b){var c,d,e;c=a.l-b.l;d=a.m-b.m+(c>>22);e=a.h-b.h+(d>>22);return Ev(c&azb,d&azb,e&bzb)}
function LI(a,b){var c;for(c=0;c<(bmb(),b.length);c++){if(a==b.charCodeAt(c)){return true}}return false}
function yP(a,b){var c;for(c=0;c<(bmb(),b.length);c++){if(a==b.charCodeAt(c)){return true}}return false}
function rJ(a,b){var c,d;if(a.n){d=Smb(a.n,b);if(d!=null){return d}}c=zJ(b);aw(c,5)&&sJ(a,b,c);return c}
function lJ(a){var b,c,d;b=new jJ;for(d=WI(a,0);d.b!=d.d.c;){c=Wv(_ub(d),10);rn(b,0,new II(c))}return b}
function Q6(a,b,c){var d,e,f,g;g=new U6(b,c);f=0;for(e=T6(g);e.G();){d=Wv(e.H(),7);Umb(a.c,d,Elb(f++))}}
function Fb(a,b,c){_b(b);if(c.G()){vmb(b,a.C(c.H()));while(c.G()){vmb(b,a.c);vmb(b,a.C(c.H()))}}return b}
function g9(a,b,c,d,e){if(d){h9(a,b)}else{d9(a,b,e);e9(a,b,c)}if(b.c.length>1){Gpb(b,a.b);V9(a.c,b)}}
function Bv(a,b,c,d,e){e.$c=a;e._c=b;e.ad=kI;e.__elementTypeId$=c;e.__elementTypeCategory$=d;return e}
function vS(a,b,c){switch(c.e){case 2:a.b=b;break;case 1:a.c=b;break;case 4:a.d=b;break;case 3:a.a=b;}}
function B6(a,b,c){var d,e;e=C6(c).g;d=w6(a,b,e).a;return d-Klb(Wv(Smb(a.c,b),24).a-Wv(Smb(a.c,c),24).a)}
function glb(a,b){if(a<b){return -1}if(a>b){return 1}if(a==b){return 0}return isNaN(a)?isNaN(b)?0:1:-1}
function Yi(a){switch(a.Y()){case 0:return Fi;case 1:return new Er(a.mb().H());default:return new gr(a);}}
function Nt(){Nt=iI;var a,b;b=!(!!Error.stackTraceLimit||'stack' in new Error);a=new _t;Mt=b?new Tt:a}
function RP(){RP=iI;OP=new DJ('intCoordinates',(xkb(),xkb(),vkb));PP=new CJ('jsonObject');QP=new HI(0,0)}
function XZ(){XZ=iI;VZ=new YZ('MIRROR_X',0);WZ=new YZ('TRANSPOSE',1);UZ=new YZ('MIRROR_AND_TRANSPOSE',2)}
function Hgb(){Hgb=iI;Fgb=new Igb(tzb,0);Egb=new Igb('INCOMING_ONLY',1);Ggb=new Igb('OUTGOING_ONLY',2)}
function Seb(){Ieb();return Bv(tv(_E,1),uyb,60,0,[meb,jeb,ieb,peb,oeb,Heb,Geb,neb,keb,leb,qeb,Eeb,Feb])}
function b3(){b3=iI;var a,b,c,d;a3=new vsb(_E);for(b=Seb(),c=0,d=b.length;c<d;++c){a=b[c];ssb(a3,a,null)}}
function Bpb(a){ypb();var b,c,d;d=1;for(c=a.mb();c.G();){b=c.H();d=31*d+(b!=null?vb(b):0);d=d|0}return d}
function Tl(a,b){Il();var c,d;ac(b,'predicate');for(d=0;a.G();d++){c=a.H();if(b.D(c)){return d}}return -1}
function Or(a,b){var c,d;c=a.c.a;d=b.ac(c);a.b.b&&(d=XH(d,Nr(a,b,c)));a.b.c&&(d=XH(d,Mr(a,b,c)));return d}
function bwb(a,b,c){var d,e;d=new ywb(b,c);e=new zwb;a.b=_vb(a,a.b,d,e);e.b||++a.c;a.b.b=false;return e.d}
function gJ(a,b,c){var d,e,f;d=new aJ;for(f=WI(c,0);f.b!=f.d.c;){e=Wv(_ub(f),10);QI(d,new II(e))}sn(a,b,d)}
function Mp(a,b){var c;if(b===a){return true}if(aw(b,144)){c=Wv(b,144);return a.P().t(c.P())}return false}
function Svb(a){var b;b=a.a.c.length;if(b>0){return Dvb(b-1,a.a.c.length),AU(a.a,b-1)}else{throw new osb}}
function p2(a){if(a.b.c.length-a.e.c.length<0){QX(a,(sN(),ZM));a.a.a=a.j.a}else{QX(a,(sN(),rN));a.a.a=0}}
function $mb(a,b){wxb(a>=0,'Negative initial capacity');wxb(b>=0,'Non-positive load factor');Ymb(this)}
function rnb(a){var b;this.e=a;this.d=new hub(this.e.e);this.a=this.d;this.b=onb(this);b=a[WAb];this[WAb]=b}
function Kkb(){++Fkb;this.n=null;this.j=null;this.i=null;this.d=null;this.b=null;this.k=null;this.a=null}
function fpb(a){var b,c,d,e;e=1;for(c=0,d=a.length;c<d;++c){b=a[c];e=31*e+(b!=null?vb(b):0);e=e|0}return e}
function Cc(a){var b,c,d,e;b={};for(d=0,e=a.length;d<e;++d){c=a[d];b[':'+(c.d!=null?c.d:''+c.e)]=c}return b}
function wO(a){uO();var b,c,d,e;for(c=xO(),d=0,e=c.length;d<e;++d){b=c[d];if(Zi(b.a,a)){return b}}return tO}
function Itb(a,b,c){var d,e,f;for(e=0,f=c.length;e<f;++e){d=c[e];if(a.b.Uc(b,d.yb())){return d}}return null}
function Rmb(a,b,c){var d,e;for(e=c.mb();e.G();){d=Wv(e.H(),21);if(a.Uc(b,d.zb())){return true}}return false}
function Wvb(a,b){var c,d,e;e=a.b;while(e){c=a.a.$b(b,e.d);if(c==0){return e}d=c<0?0:1;e=e.a[d]}return null}
function Ge(a,b){var c,d;c=Wv(Wmb(a.a,b),19);if(!c){return null}d=a.b.Z();d.jb(c);a.b.c-=c.Y();c.Q();return d}
function y0(a,b,c){var d;d=Wv(b.B(a),9);while(d.g==(CX(),zX)){!d.n&&(d.n=new ntb);Wmb(d.n,c);d=Wv(b.B(d),9)}}
function RH(a,b){var c;if(UH(a)&&UH(b)){c=a-b;if(!isNaN(c)){return c}}return Iv(UH(a)?YH(a):a,UH(b)?YH(b):b)}
function OH(a){var b;if(aw(a,46)){return a}b=a&&a.__gwt$exception;if(!b){b=new kt(a);Ot(b,a);MH(a,b)}return b}
function p6(a){var b,c,d;b=0;for(d=new Tob(a.c);d.a<d.c.c.length;){c=Wv(Rob(d),226);b+=b6(a,c.a,c.b)}return b}
function pT(a){var b;b=new DT(a);RT(a.a,nT,new opb(Bv(tv(JA,1),syb,160,0,[b])));!!b.d&&vU(b.f,b.d);return b.f}
function w6(a,b,c){switch(c.e){case 1:return Wv(Smb(a.d,b),24);case 3:return Wv(Smb(a.j,b),24);}return Elb(0)}
function M5(a,b,c){if(!a.d[b.k][c.k]){L5(a,b,c);a.d[b.k][c.k]=true;a.d[c.k][b.k]=true}return a.a[b.k][c.k]}
function Ds(a,b,c){var d;d=b.$b(c,a.b);return d<0?!a.e?a:Wv(Sb(Ds(a.e,b,c),a),206):d==0?a:!a.g?null:Ds(a.g,b,c)}
function rb(a,b){return ew(a)?emb(a,b):cw(a)?(Dxb(a),a===b):bw(a)?(Dxb(a),a===b):_v(a)?a.t(b):zv(a)?a===b:a===b}
function vQ(a,b){return emb(a.b,b)||dmb(a.b,b)&&((bmb(),b.length)==pmb(a.b)||jmb(a.b,pmb(a.b)-b.length-1)==46)}
function L6(a,b){var c,d,e;c=0;for(e=nX(a,b).mb();e.G();){d=Wv(e.H(),7);c+=rJ(d,(Rib(),Bib))!=null?1:0}return c}
function Xvb(a,b){var c,d,e;d=null;e=a.b;while(e){c=a.a.$b(b,e.d);if(c>=0){e=e.a[1]}else{d=e;e=e.a[0]}}return d}
function Yvb(a,b){var c,d,e;d=null;e=a.b;while(e){c=a.a.$b(b,e.d);if(c<=0){e=e.a[0]}else{d=e;e=e.a[1]}}return d}
function u0(a,b,c,d){var e,f;for(f=a.mb();f.G();){e=Wv(f.H(),33);e.i.a=b.a+(d.a-e.j.a)/2;e.i.b=b.b;b.b+=e.j.b+c}}
function o$(a,b){var c;if(a.c.length==0){return}c=Wv(FU(a,xv(qB,Nzb,9,a.c.length,0,1)),51);lpb(c,new z$);l$(c,b)}
function t$(a,b){var c;if(a.c.length==0){return}c=Wv(FU(a,xv(qB,Nzb,9,a.c.length,0,1)),51);lpb(c,new C$);l$(c,b)}
function _Z(a){var b,c;b=a.g;if(b==(CX(),xX)){c=Wv(rJ(a,(Rib(),hib)),32);return c==(sN(),$M)||c==pN}return false}
function Gc(a,b){var c;Dxb(b);c=a[':'+b];xxb(!!c,'Enum constant undefined: %s',Bv(tv(UF,1),syb,1,4,[b]));return c}
function Zb(a,b,c){if(!a){throw new slb(fc('lowerEndpoint (%s) > upperEndpoint (%s)',Bv(tv(UF,1),syb,1,4,[b,c])))}}
function kv(a){ev();throw new zu("Unexpected typeof result '"+a+"'; please report this bug to the GWT team")}
function tN(a){switch(a.e){case 1:return pN;case 2:return rN;case 3:return $M;case 4:return ZM;default:return qN;}}
function vK(a){switch(a.e){case 2:return pK;case 1:return oK;case 4:return nK;case 3:return rK;default:return qK;}}
function Dkb(a){if(a>=48&&a<58){return a-48}if(a>=97&&a<97){return a-97+10}if(a>=65&&a<65){return a-65+10}return -1}
function td(a,b){var c,d;for(d=Ep(Be(a.P()));d.b.G();){c=Wv(zm(d,d.b.H()),19);if(c.kb(b)){return true}}return false}
function js(a){var b;if(!is(a)){throw new nvb}b=new fs(a.c,a.a);a.b=b;a.a.i==a.c.a?(a.a=null):(a.a=a.a.i);return b}
function pp(a,b){mp();var c;if(a===b){return true}else if(aw(b,57)){c=Wv(b,57);return mr(nj(a),c.bb())}return false}
function Gq(a,b,c,d){Dq();Mh(c,'oldCount');Mh(d,'newCount');if(a.Cb(b)==c){a.Gb(b,d);return true}else{return false}}
function Bh(a,b,c,d,e){_b(c);_b(e);return Rr(new Ur(a.c,pk(a.b,new sk(a.d,true,b,c,false,null,(Gh(),Fh))),a.a),d,e)}
function ck(a){hi();switch(a.Y()){case 0:return kr(),jr;case 1:return new Gr(a.mb().H());default:return new lr(a);}}
function PH(a,b){var c;if(UH(a)&&UH(b)){c=a+b;if(ezb<c&&c<dzb){return c}}return SH(Gv(UH(a)?YH(a):a,UH(b)?YH(b):b))}
function WH(a,b){var c;if(UH(a)&&UH(b)){c=a*b;if(ezb<c&&c<dzb){return c}}return SH(Kv(UH(a)?YH(a):a,UH(b)?YH(b):b))}
function XH(a,b){var c;if(UH(a)&&UH(b)){c=a-b;if(ezb<c&&c<dzb){return c}}return SH(Mv(UH(a)?YH(a):a,UH(b)?YH(b):b))}
function sK(){sK=iI;qK=new wK(szb,0);pK=new wK(pzb,1);oK=new wK(ozb,2);nK=new wK('DOWN',3);rK=new wK('UP',4)}
function NK(){NK=iI;MK=new OK(szb,0);KK=new OK('POLYLINE',1);JK=new OK('ORTHOGONAL',2);LK=new OK('SPLINES',3)}
function eL(){eL=iI;cL=new fL('INHERIT',0);bL=new fL('INCLUDE_CHILDREN',1);dL=new fL('SEPARATE_CHILDREN',2)}
function G8(){G8=iI;D8=TQ(RQ(new WQ,(d0(),p_)),I_);E8=PQ(TQ(SQ(new WQ,j_),h_),i_);F8=PQ(UQ(new WQ,k_),i_)}
function P8(){P8=iI;M8=TQ(RQ(new WQ,(d0(),p_)),I_);N8=PQ(TQ(SQ(new WQ,j_),h_),i_);O8=PQ(UQ(new WQ,k_),i_)}
function deb(a){this.a=new Wub;this.d=new Wub;this.b=new Wub;this.c=new Wub;this.g=new Wub;this.i=new Wub;this.f=a}
function UV(a,b,c,d,e,f){this.e=new GU;this.f=(djb(),cjb);vU(this.e,a);this.d=b;this.a=c;this.b=d;this.f=e;this.c=f}
function hpb(a,b,c,d,e,f,g,h){var i;i=c;while(f<g){i>=d||b<c&&h.$b(a[b],a[i])<=0?Av(e,f++,a[b++]):Av(e,f++,a[i++])}}
function v0(a,b,c,d,e){var f,g;for(g=a.mb();g.G();){f=Wv(g.H(),33);f.i.a=b.a;f.i.b=e?b.b:b.b+d.b-f.j.b;b.a+=f.j.a+c}}
function gcb(a,b){$bb();var c,d;for(d=Uh(gX(a));Cm(d);){c=Wv(Dm(d),12);if(c.d.f==b||c.c.f==b){return c}}return null}
function fdb(a,b,c){var d,e,f;d=0;for(f=WI(a,0);f.b!=f.d.c;){e=Ixb(Yv(_ub(f)));if(e>c){break}else e>=b&&++d}return d}
function sn(a,b,c){var d,e,f,g;Dxb(c);g=false;f=WI(a,b);for(e=WI(c,0);e.b!=e.d.c;){d=_ub(e);$ub(f,d);g=true}return g}
function Uf(a,b){var c,d,e;if(b.V()){return false}e=a.Y();c=a.d.jb(b);if(c){d=a.d.Y();a.f.c+=d-e;e==0&&Vf(a)}return c}
function qJ(a,b){var c;if(!b){return a}c=!b.n?(ypb(),ypb(),wpb):b.n;c.V()||(!a.n?(a.n=new ptb(c)):he(a.n,c));return a}
function Gb(b,c,d){var e;try{Fb(b,c,d)}catch(a){a=OH(a);if(aw(a,181)){e=a;throw new ukb(e)}else throw NH(a)}return c}
function Qb(b,c,d){var e;try{Pb(b,c,d)}catch(a){a=OH(a);if(aw(a,181)){e=a;throw new ukb(e)}else throw NH(a)}return c}
function NH(a){var b;if(aw(a,164)){b=Wv(a,164);if(gw(b.b)!==gw((it(),ht))){return gw(b.b)===gw(ht)?null:b.b}}return a}
function SW(a,b){var c;c=Wv(rJ(hX(a),(Rib(),zib)),9);while(c){if(c==b){return true}c=Wv(rJ(hX(c),zib),9)}return false}
function EZ(a){switch(Wv(rJ(a,(Rib(),mib)),140).e){case 1:sJ(a,mib,(Hhb(),Ehb));break;case 2:sJ(a,mib,(Hhb(),Ghb));}}
function Kk(a){hi();switch(a.c){case 0:return kr(),jr;case 1:return new Gr(Sl(new jtb(a)));default:return new Jk(a);}}
function Ti(a){Gi();var b,c;for(b=0,c=a.length;b<c;b++){if(a[b]==null){throw new Wlb('at index '+b)}}return new opb(a)}
function $4(a,b,c){if(b.length==0||c.length==0){return 0}a.e?(a.b=new y5(a.c)):(a.b=new H5(a.c));return a.b.Gc(b,c)}
function pI(a){if(a.i==null){throw new ulb('The task has not begun yet.')}if(!a.b){a.c<a.j&&qI(a,a.j-a.c);a.b=true}}
function DR(a,b){var c,d;for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),27);BU(a.b.b,c.b);PR(Wv(c.a,78),Wv(c.b,25))}}
function aU(a,b){var c,d;for(d=new Tob(a.a);d.a<d.c.c.length;){c=Wv(Rob(d),222);if(YT(c,b)){return}}vU(a.a,new _T(b))}
function aV(a){var b,c,d;b=new GU;for(d=new Tob(a.b);d.a<d.c.c.length;){c=Wv(Rob(d),251);xU(b,Wv(c.Ac(),19))}return b}
function Q0(a,b){var c,d,e;e=new GU;for(d=nX(a,b).mb();d.G();){c=Wv(d.H(),7);e.c[e.c.length]=c}Gpb(e,new V0);return e}
function iX(a){var b,c,d;b=new GU;for(d=new Tob(a.f);d.a<d.c.c.length;){c=Wv(Rob(d),7);vU(b,c.b)}return _b(b),new Vh(b)}
function mX(a){var b,c,d;b=new GU;for(d=new Tob(a.f);d.a<d.c.c.length;){c=Wv(Rob(d),7);vU(b,c.e)}return _b(b),new Vh(b)}
function Elb(a){var b,c;if(a>-129&&a<128){b=a+128;c=(Glb(),Flb)[b];!c&&(c=Flb[b]=new wlb(a));return c}return new wlb(a)}
function R5(a){var b,c;b=Z4(a.b,a.d);c=$xb;while(c>b){S5(a,a.d);if(b==0){c=0;break}W5(a);U5(a);c=b;b=Z4(a.b,a.d)}a.c=c}
function yvb(){tvb();var a,b,c;c=svb+++ixb();a=hw(Math.floor(c*FAb))&bBb;b=hw(c-a*aBb);this.a=a^1502;this.b=b^_Ab}
function vb(a){return ew(a)?Pxb(a):cw(a)?hw((Dxb(a),a)):bw(a)?Ckb((Dxb(a),a))?1231:1237:_v(a)?a.v():zv(a)?txb(a):txb(a)}
function AQ(a,b,c){var d,e,f;e=new jQ;e.d=c;d=UP(e,b);f=new dR;Ckb(Ixb(Xv(rJ(d,yQ))))?YQ(f,d,new sI):BQ(a,f,d);ZP(e,d)}
function E6(a,b,c,d){var e,f,g,h;h=new U6(b,d);g=0;for(f=T6(h);f.G();){e=Wv(f.H(),7);Umb(a.i,e,Elb(g++))}Umb(c,b,Elb(g))}
function c6(a,b){var c,d,e,f,g;c=0;g=0;for(e=0,f=b.length;e<f;++e){d=b[e];c=i6(a,c,d,(sN(),ZM),a.f);g=i6(a,g,d,rN,a.n)}}
function pJ(a,b){var c,d,e,f;if(!a.n){return}for(d=0,e=b.length;d<e;++d){c=b[d];f=Smb(a.n,c);if(f!=null){c.nc();c.oc()}}}
function L2(a,b){var c,d,e;for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),75);e=X2(a.a);R2(a.a,e,c.k,c.j);aeb(c,e,true)}}
function M2(a,b){var c,d,e;for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),75);e=W2(a.a);R2(a.a,e,c.k,c.j);aeb(c,e,true)}}
function PW(a){var b,c;c=Wv(rJ(a,(eM(),sL)),59);if(c==(sK(),qK)){b=Wv(rJ(a,(Rib(),Rhb)),15).a;return b>=1?pK:nK}return c}
function Cm(a){_b(a.b);if(a.b.G()){return true}while(a.a.G()){_b(a.b=a.Wb(a.a.H()));if(a.b.G()){return true}}return false}
function m7(a){if(a.d!=a.c.d||a.i!=a.g.d){a.a.c=xv(UF,syb,1,0,4,1);xU(a.a,a.c);xU(a.a,a.g);a.d=a.c.d;a.i=a.g.d}return a.a}
function Yf(a){var b;if(a.b){Yf(a.b);if(a.b.d!=a.c){throw new nsb}}else if(a.d.V()){b=Wv(Smb(a.f.b,a.e),19);!!b&&(a.d=b)}}
function H9(a,b,c,d,e){var f,g,h,i;i=Co(a);g9(b,i,d,e,c);f=0;for(h=new Tob(i);h.a<h.c.c.length;){g=Wv(Rob(h),9);a[f++]=g}}
function oP(a){var b,c,d;d=Wv(vW(a.a,(eM(),DL)),15).a;for(c=new Tob(uW(a.a));c.a<c.c.c.length;){b=Wv(Rob(c),626);qP(a,b,d)}}
function WQ(){var a,b;this.a=new HU(6);for(b=0;b<6;b++){vU(this.a,(a=Wv(Hkb(mC),11),new atb(a,Wv(exb(a,a.length),11),0)))}}
function W5(a){var b,c,d;d=false;for(c=0;c<a.d.length;c++){a.j=(b=new N5(a.e,a.d,c,0),new b7(c,a.d,b));d=d|O5(a,c)}return d}
function H8(a,b,c){var d,e;e=a.a.c;for(d=e.c.length;d<c;d++){uU(e,0,new sY(a.a))}rX(b,Wv(yU(e,e.c.length-c),16));a.b[b.k]=c}
function hdb(a,b){var c,d;c=WI(a,0);while(c.b!=c.d.c){d=Ixb(Yv(_ub(c)));if(d==b){return}else if(d>b){avb(c);break}}$ub(c,b)}
function dub(a,b,c){var d;d=Utb(a.a,b);Wtb(a.a,b,c===undefined?null:c);if(d===undefined){++a.c;msb(a.b)}else{++a.d}return d}
function qgb(a,b,c){if((b-a<=0?0-(b-a):b-a)<uAb||(c-a<=0?0-(c-a):c-a)<uAb){return true}return b-a>uAb?a-c>uAb:c-a>uAb}
function Qgb(a){switch(a.e){case 0:return Kgb;case 1:return Lgb;case 2:return Mgb;case 3:return Ngb;default:return Ogb;}}
function uS(a,b){switch(b.e){case 2:return a.b;case 1:return a.c;case 4:return a.d;case 3:return a.a;default:return false;}}
function vN(a){sN();switch(a.e){case 4:return $M;case 1:return ZM;case 3:return pN;case 2:return rN;default:return qN;}}
function c7(a,b){if(b==a.c){return a.d}else if(b==a.d){return a.c}else{throw new slb('Node '+b+' not part of edge '+a)}}
function zO(a,b){var c;if(Zsb(a.a,b)){return Wv(Zsb(a.a,b)?a.b[b.e]:null,62)}else{c=new ZN;Wsb(a.a,b);usb(a,b.e,c);return c}}
function Zeb(a,b){var c,d,e,f;f=a.g.tb();c=0;while(f.G()){d=Ixb(Yv(f.H()));e=d-b;if(e>RAb){return c}else e>SAb&&++c}return c}
function Usb(a){var b,c,d,e;c=(b=Wv(Hkb((d=a.$c,e=d.f,e==IF?d:e)),11),new atb(b,Wv(exb(b,b.length),11),0));Wsb(c,a);return c}
function yR(a,b){var c,d;for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),27);vU(a.b.b,Wv(c.b,25));OR(Wv(c.a,78),Wv(c.b,25))}}
function gpb(a,b,c,d){var e,f,g;for(e=b+1;e<c;++e){for(f=e;f>b&&d.$b(a[f-1],a[f])>0;--f){g=a[f];Av(a,f,a[f-1]);Av(a,f-1,g)}}}
function k3(a){var b,c;if(!MM(Wv(rJ(a,(eM(),TL)),28))){for(c=new Tob(a.f);c.a<c.c.c.length;){b=Wv(Rob(c),7);QX(b,(sN(),qN))}}}
function oX(a,b){switch(b.e){case 1:return pl(a.f,(LX(),GX));case 2:return pl(a.f,(LX(),IX));default:return ypb(),ypb(),vpb;}}
function oW(a,b){if(yJ(b,(eM(),cM))){return rJ(a.e,(Rib(),Jib))}else if(yJ(b,LL)){return rJ(a.e,(Rib(),tib))}return rJ(a.e,b)}
function I5(a,b,c,d){var e,f,g;f=b;e=c-1;while(f<=e){g=(f+e)/2|0;if(a[g]==d){return g}else a[g]<d?(f=g+1):(e=g-1)}return -f-1}
function Ve(a,b,c){var d,e;for(e=a.mb();e.G();){d=e.H();if(gw(b)===gw(d)||b!=null&&rb(b,d)){c&&e.I();return true}}return false}
function epb(a,b,c){var d;xxb(b<=c,'%s > %s',Bv(tv(UF,1),syb,1,4,[Elb(b),Elb(c)]));d=a.length;c=c<d?c:d;Gxb(b,c,d);return c-b}
function aW(a,b){var c,d,e;c=a;e=0;do{if(c==b){return e}d=Wv(rJ(c,(Rib(),zib)),9);if(!d){throw new rlb}c=hX(d);++e}while(true)}
function U5(a){var b,c,d;d=false;for(c=a.d.length-1;c>=0;c--){a.j=(b=new N5(a.e,a.d,c,1),new b7(c,a.d,b));d=d|O5(a,c)}return d}
function k6(a){this.f=(mp(),new ntb);this.n=new ntb;this.k=new ntb;this.g=new vtb;this.i=new Vr((Tq(),Sq));this.j=a;c6(this,a)}
function vsb(a){var b;this.a=(b=Wv(a.e&&a.e(),11),new atb(b,Wv(exb(b,b.length),11),0));this.b=xv(UF,syb,1,this.a.a.length,4,1)}
function jf(a,b){var c;if(b===a){return true}if(!aw(b,18)){return false}c=Wv(b,18);if(c.Y()!=a.Y()){return false}return a.lb(c)}
function Reb(a){Ieb();switch(a.e){case 1:return meb;case 2:return ieb;case 3:return oeb;case 4:return Geb;default:return Feb;}}
function pgb(a,b){switch(b.e){case 1:return a.e.d;case 2:return a.e.c;case 3:return a.e.a;case 4:return a.e.b;default:return 0;}}
function xO(){uO();return Bv(tv(Oz,1),uyb,67,0,[rO,qO,sO,iO,hO,jO,mO,lO,kO,pO,oO,nO,fO,eO,gO,cO,bO,dO,_N,$N,aO,tO])}
function zM(){zM=iI;yM=new AM(szb,0);xM=new AM('JUSTIFIED',1);uM=new AM('BEGIN',2);vM=new AM(qzb,3);wM=new AM('END',4)}
function DN(){DN=iI;BN=new EN('PORTS',0);CN=new EN('PORT_LABELS',1);AN=new EN('NODE_LABELS',2);zN=new EN('MINIMUM_SIZE',3)}
function kP(){kP=iI;jP=new lP('UNKNOWN',0);gP=new lP('ABOVE',1);hP=new lP('BELOW',2);iP=new DJ('de.cau.cs.kieler.labelSide',jP)}
function Qjb(){Qjb=iI;Njb=new Rjb('EQUALLY_DISTRIBUTED',0);Pjb=new Rjb('NORTH_STACKED',1);Ojb=new Rjb('NORTH_SEQUENCE',2)}
function gI(){fI={};!Array.isArray&&(Array.isArray=function(a){return Object.prototype.toString.call(a)==='[object Array]'})}
function SR(a,b){return Ws(),Ws(),((a-b>0?a-b:-(a-b))<=$yb||a==b||isNaN(a)&&isNaN(b)?0:a<b?-1:a>b?1:Ys(isNaN(a),isNaN(b)))>0}
function TR(a,b){return Ws(),Ws(),((a-b>0?a-b:-(a-b))<=$yb||a==b||isNaN(a)&&isNaN(b)?0:a<b?-1:a>b?1:Ys(isNaN(a),isNaN(b)))<0}
function Veb(a){var b,c;a.d||cfb(a);c=new jJ;b=a.b.mb();b.H();while(b.G()){QI(c,Wv(b.H(),92).a)}Bxb(c.b!=0);$I(c,c.c.b);return c}
function $db(a){var b,c,d,e;e=new Wub;b=new IU(a.c);Dpb(b);for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),7);e.a.db(c,e)}return e}
function Np(a,b){var c,d,e;_b(b);for(d=(e=a.g,Wv(!e?(a.g=new En(a)):e,20)).mb();d.G();){c=Wv(d.H(),21);Fd(b,c.zb(),c.yb())}return b}
function mf(a,b){var c,d,e;if(aw(b,21)){c=Wv(b,21);d=c.yb();e=rp(a.qb(),d);return Tb(e,c.zb())&&(e!=null||a.qb().R(d))}return false}
function Yeb(a,b){var c,d,e;e=a.g.tb();while(e.G()){c=Ixb(Yv(e.H()));d=c-b<=0?0-(c-b):c-b;if(d<RAb){return e.L()-1}}return a.g.Y()}
function Vfb(a){var b,c;for(c=new Tob(a.a);c.a<c.c.c.length;){b=Wv(Rob(c),9);if(b.g==(CX(),AX)||b.g==wX){return false}}return true}
function nI(a,b,c){if(a.b){throw new ulb('The task is already done.')}else if(a.i!=null){return false}else{a.i=b;a.j=c;return true}}
function A5(a,b){if(a.f<b.f){return -1}else if(a.f>b.f){return 1}else if(a.g<b.g){return -1}else if(a.g>b.g){return 1}return a.b-b.b}
function S8(a,b){if(b.c==a){return b.d}else if(b.d==a){return b.c}throw new slb('Input edge is not connected to the input port.')}
function q5(a){var b;if(a.c==0){return}b=Wv(yU(a.a,a.b),128);b.b==1?(++a.b,a.b<a.a.c.length&&u5(Wv(yU(a.a,a.b),128))):--b.b;--a.c}
function ZU(a,b){a.b.a=Qlb(a.b.a,b.c);a.b.b=Qlb(a.b.b,b.d);a.a.a=Nlb(a.a.a,b.c);a.a.b=Nlb(a.a.b,b.d);return a.c[a.c.length]=b,true}
function vbb(a,b,c){var d,e;d=Ixb(a.n[b.f.k])+Ixb(a.d[b.f.k])+b.i.b+b.a.b;e=Ixb(a.n[c.f.k])+Ixb(a.d[c.f.k])+c.i.b+c.a.b;return e-d}
function Y5(a,b,c,d){var e,f,g;e=false;if($6(a.j,c,d)){a7(a.j,a.d[b][c],a.d[b][d]);f=a.d[b];g=f[d];f[d]=f[c];f[c]=g;e=true}return e}
function fX(a,b,c){var d,e,f,g,h;h=hX(a);e=h.a;d=Wv(rJ(h,(Rib(),Xhb)),15).a;f=h.d;g=a.i;b&&(g.a=g.a-e.b-d-f.a);c&&(g.b=g.b-e.d-d-f.b)}
function Q$(a,b){var c,d,e;for(d=Uh(gX(a));Cm(d);){c=Wv(Dm(d),12);e=Wv(b.B(c),9);return new $c(_b(e.i.b+e.j.b/2))}return zb(),zb(),yb}
function ifb(a){var b,c,d,e,f;d=gfb(a);b=rAb;f=0;e=0;while(b>0.5&&f<50){e=ofb(d);c=$eb(d,e,true);b=Jlb(c.b);++f}return $eb(a,e,false)}
function jfb(a){var b,c,d,e,f;d=gfb(a);b=rAb;f=0;e=0;while(b>0.5&&f<50){e=nfb(d);c=$eb(d,e,true);b=Jlb(c.a);++f}return $eb(a,e,false)}
function QR(a){var b,c,d;this.a=new Wub;this.e=new vtb;this.f=0;for(c=0,d=a.length;c<d;++c){b=a[c];!this.g&&(this.g=b);OR(this,b)}}
function dfb(a){Teb(this);this.c=a.c;this.f=a.f;this.e=a.e;this.k=a.k;this.d=a.d;this.g=Eo(a.g);this.j=a.j;this.i=a.i;this.b=Eo(a.b)}
function oU(a){switch(a.e){case 1:return sK(),rK;case 4:return sK(),oK;case 2:return sK(),pK;case 3:return sK(),nK;}return sK(),qK}
function Xdb(a,b){if(_db(a,b)){stb(a.g,b);return true}b.g!=(sN(),qN)&&stb(a.i,b);b.e.c.length==0?stb(a.c,b):stb(a.b,b);return false}
function wU(a,b){var c,d;Fxb(0,a.c.length);c=Ye(b,xv(UF,syb,1,b.a.Y(),4,1));d=c.length;if(d==0){return false}gxb(a.c,0,c);return true}
function Zkb(a,b){var c=0;while(!b[c]||b[c]==''){c++}var d=b[c++];for(;c<b.length;c++){if(!b[c]||b[c]==''){continue}d+=a+b[c]}return d}
function yt(){var a;if(ut!=0){a=pt();if(a-vt>2000){vt=a;wt=$wnd.setTimeout(Et,10)}}if(ut++==0){Ht((Gt(),Ft));return true}return false}
function kS(a){var b,c;for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);b.j.d=-b.j.d-b.j.c;!!b.o&&(b.g.a=-b.g.a+b.o.j.c)}fS(a)}
function D2(a,b){var c;c=a;while(b.b<b.d.Y()&&c==a){c=(Bxb(b.b<b.d.Y()),Wv(b.d.sb(b.c=b.b++),7)).g}c==a||(Bxb(b.b>0),b.a.sb(b.c=--b.b))}
function a$(a){var b;if(!LM(Wv(rJ(a,(eM(),TL)),28))){return}b=a.c;b$((Cxb(0,b.c.length),Wv(b.c[0],16)));b$(Wv(yU(b,b.c.length-1),16))}
function NV(a,b,c){nI(c,'Compound graph preprocessor',1);a.a=new xk;RV(a,b,null);MV(a,b);sJ(b,(Rib(),bib),a.a);a.a=null;Ymb(a.b);pI(c)}
function P0(a){var b,c;b=Wv(Dm(Uh(iX(a))),12);c=Wv(Dm(Uh(mX(a))),12);return !Ckb(Ixb(Xv(rJ(b,(Rib(),Iib)))))||!Ckb(Ixb(Xv(rJ(c,Iib))))}
function O6(a,b,c){if(b.g==(CX(),AX)&&c.g==zX){a.d=L6(b,(sN(),pN));a.b=L6(b,$M)}if(c.g==AX&&b.g==zX){a.d=L6(c,(sN(),$M));a.b=L6(c,pN)}}
function _8(a,b,c){var d,e,f,g;f=b.g;g=c.g;if(f!=g){return f.e-g.e}else{d=a.a[b.k];e=a.a[c.k];return !d&&!e?0:!d?-1:!e?1:glb(d.a,e.a)}}
function jab(a,b,c,d){var e,f,g,h;f=b;e=c-1;while(f<=e){g=f+e>>>1;h=a[g];if(h<d){f=g+1}else if(h>d){e=g-1}else{return g}}return -(f+1)}
function Id(a){return aw(a,137)?(ypb(),new dsb(Wv(a,137))):aw(a,18)?(ypb(),new Frb(Wv(a,18))):aw(a,20)?Hpb(Wv(a,20)):(ypb(),new zqb(a))}
function Kd(a,b,c){return aw(c,137)?new Lg(a,b,Wv(c,137)):aw(c,18)?new Kg(a,b,Wv(c,18)):aw(c,20)?Ld(a,b,Wv(c,20),null):new _f(a,b,c,null)}
function tn(b,c){var d;d=b.ub(c);try{return d.H()}catch(a){a=OH(a);if(aw(a,74)){throw new okb("Can't get element "+c)}else throw NH(a)}}
function rp(b,c){mp();_b(b);try{return b.cb(c)}catch(a){a=OH(a);if(aw(a,119)){return null}else if(aw(a,76)){return null}else throw NH(a)}}
function Qu(f,a){var b=f.a;var c;a=String(a);b.hasOwnProperty(a)&&(c=b[a]);var d=(ev(),dv)[typeof c];var e=d?d(c):kv(typeof c);return e}
function kgb(a,b,c,d){if(b<c){a.b=0.5*(b+c);a.p=UAb*a.b+0.9*b;a.a=UAb*a.b+0.9*c}else{a.b=0.5*(b+d);a.p=UAb*a.b+0.9*d;a.a=UAb*a.b+0.9*b}}
function Vr(a){Ch.call(this,a);this.b=new sk(a,false,null,(Gh(),Fh),false,null,Fh);this.a=new Os(null,1);ds(this.a,this.a);this.c=new Vs}
function xT(a){vT();this.c=new GU;this.d=a;switch(a.e){case 0:case 2:this.a=Epb(uT);this.b=Uzb;break;case 3:case 1:this.a=uT;this.b=Vzb;}}
function iK(){iK=iI;cK=new jK('AUTOMATIC',0);fK=new jK(ozb,1);gK=new jK(pzb,2);hK=new jK('TOP',3);dK=new jK('BOTTOM',4);eK=new jK(qzb,5)}
function Pxb(a){Nxb();var b,c,d;c=':'+a;d=Mxb[c];if(!(d===undefined)){return d}d=Kxb[c];b=d===undefined?Oxb(a):d;Qxb();Mxb[c]=b;return b}
function bk(a,b,c,d,e,f,g){hi();var h,i;i=g.length+6;h=new HU(i);zpb(h,Bv(tv(UF,1),syb,1,4,[a,b,c,d,e,f]));zpb(h,g);return Yj(new Tob(h))}
function GZ(a){var b;b=Wv(rJ(a,(eM(),JL)),18);if(b.V()){return}if(b.kb((oM(),gM))){b.nb(gM);b.ib(iM)}else if(b.kb(iM)){b.nb(iM);b.ib(gM)}}
function HZ(a){var b;b=Wv(rJ(a,(eM(),JL)),18);if(b.V()){return}if(b.kb((oM(),nM))){b.nb(nM);b.ib(lM)}else if(b.kb(lM)){b.nb(lM);b.ib(nM)}}
function f$(a,b){var c,d,e,f;e=a.g;c=Ixb(Yv(rJ(a,(Rib(),Cib))));f=b.g;d=Ixb(Yv(rJ(b,Cib)));return f!=(CX(),xX)?-1:e!=xX?1:c==d?0:c<d?-1:1}
function g6(a,b,c){var d,e;d=Slb(h6(a,b.d),h6(a,b.c));e=Plb(h6(a,b.d),h6(a,b.c));return $s(Or(Bh(c,Elb(d),(Gh(),Fh),Elb(e),Fh),(qs(),ps)))}
function qp(b,c){mp();_b(b);try{return b.R(c)}catch(a){a=OH(a);if(aw(a,119)){return false}else if(aw(a,76)){return false}else throw NH(a)}}
function Qh(b,c){Oh();_b(b);try{return hnb(b,c)}catch(a){a=OH(a);if(aw(a,119)){return false}else if(aw(a,76)){return false}else throw NH(a)}}
function nab(a,b){if(a.e<b.e){return -1}else if(a.e>b.e){return 1}else if(a.f<b.f){return -1}else if(a.f>b.f){return 1}return txb(a)-txb(b)}
function QZ(a){switch(a.e){case 1:return sN(),rN;case 4:return sN(),$M;case 3:return sN(),ZM;case 2:return sN(),pN;default:return sN(),qN;}}
function Ki(a){var b,c;b=cxb(a.c,a.c.length);switch(b.length){case 0:return Fi;case 1:c=new Er(b[0]);return c;default:return new gr(Ti(b));}}
function EY(a){var b,c,d,e;d=xv(ow,syb,64,a.c.length,0,1);e=0;for(c=new Tob(a);c.a<c.c.c.length;){b=Wv(Rob(c),64);d[e++]=b}return new CY(d)}
function sW(a){var b,c;if(!a.b){a.b=Do(a.a.b.c.length);for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),33);vU(a.b,new yW(b))}}return a.b}
function K6(a,b){var c,d,e;if(a.e){return 1}c=0;for(e=new Tob(b.f);e.a<e.c.c.length;){d=Wv(Rob(e),7);c+=d.b.c.length+d.e.c.length}return c}
function I6(a){var b,c,d,e;b=false;e=false;for(d=new Tob(a.f);d.a<d.c.c.length;){c=Wv(Rob(d),7);b=b|c.g==(sN(),ZM);e=e|c.g==rN}return b&&e}
function bV(a){var b,c;this.b=new GU;this.c=a;this.a=false;for(c=new Tob(a.b);c.a<c.c.c.length;){b=Wv(Rob(c),9);this.a=this.a|b.g==(CX(),AX)}}
function uX(a){cX.call(this);this.g=(CX(),AX);this.f=(Mh(6,Vyb),new HU(6));this.c=(Mh(2,Vyb),new HU(2));this.e=new ZW;this.b=new ZW;this.a=a}
function ffb(a,b,c,d,e,f){Teb(this);this.e=a;this.f=b;this.d=c;this.c=d;this.g=e;this.b=f;this.j=Ixb(Yv(e.mb().H()));this.i=Ixb(Yv(rl(e)))}
function Lh(a,b){if(a==null){throw new Wlb('null key in entry: null='+b)}else if(b==null){throw new Wlb('null value in entry: '+a+'=null')}}
function Hab(){Hab=iI;Eab=VQ(new WQ,(d0(),v_));Fab=new DJ('linearSegments.inputPrio',Elb(0));Gab=new DJ('linearSegments.outputPrio',Elb(0))}
function Cd(a){var b,c,d,e;for(c=(e=(new aob(a.b)).a.bb().mb(),new fob(e));c.a.G();){b=(d=Wv(c.a.H(),21),Wv(d.zb(),19));b.Q()}Ymb(a.b);a.c=0}
function WI(a,b){var c,d;Fxb(b,a.b);if(b>=a.b>>1){d=a.c;for(c=a.b;c>b;--c){d=d.b}}else{d=a.a.a;for(c=0;c<b;++c){d=d.a}}return new cvb(a,b,d)}
function cU(a,b){var c,d,e;e=new FI;for(d=a.mb();d.G();){c=Wv(d.H(),55);UT(c,e.a,0);e.a+=c.e.a+b;e.b=Nlb(e.b,c.e.b)}e.b>0&&(e.b+=b);return e}
function eU(a,b){var c,d,e;e=new FI;for(d=a.mb();d.G();){c=Wv(d.H(),55);UT(c,0,e.b);e.b+=c.e.b+b;e.a=Nlb(e.a,c.e.a)}e.a>0&&(e.a+=b);return e}
function tub(a,b,c){var d,e,f;e=Wv(Smb(a.c,b),176);if(!e){d=new Jub(a,b,c);Umb(a.c,b,d);Gub(d);return null}else{f=job(e,c);uub(a,e);return f}}
function y3(a,b){if(!Keb(a.b).kb(b.c)){return false}return Oeb(a.b)?!(rgb(b.d,a.c,a.a)&&rgb(b.a,a.c,a.a)):rgb(b.d,a.c,a.a)&&rgb(b.a,a.c,a.a)}
function s6(a,b){return a.c<b.c||a.c==b.c&&d6(a.a)&&d6(b.a)&&h6(a.d,q6(a.a,a.b))>h6(a.d,q6(b.a,b.b))?-1:a.c==b.c&&q6(a.a,a.b)==q6(a.a,a.b)?0:1}
function L5(a,b,c){if(a.e){switch(a.b){case 1:g5(a.c,b,c);break;case 0:h5(a.c,b,c);}}else{e5(a.c,b,c)}a.a[b.k][c.k]=a.c.i;a.a[c.k][b.k]=a.c.e}
function LW(a,b,c){switch(c.e){case 1:a.a=b.a/2;a.b=0;break;case 2:a.a=b.a;a.b=b.b/2;break;case 3:a.a=b.a/2;a.b=b.b;break;case 4:a.a=0;a.b=b.b/2;}}
function Jeb(a){switch(a.e){case 8:return sN(),$M;case 9:return sN(),pN;case 10:return sN(),ZM;case 11:return sN(),rN;default:return sN(),qN;}}
function Qt(a){var b,c,d;b='Ot';d=Slb(a.length,5);for(c=0;c<d;c++){if(emb(a[c].d,b)){a.length>=c+1&&(a.splice(0,c+1),undefined);break}}return a}
function Vv(a,b){if(ew(a)){return !!Uv[b]}else if(a._c){return !!a._c[b]}else if(cw(a)){return !!Tv[b]}else if(bw(a)){return !!Sv[b]}return false}
function jQ(){RP();this.i=(mp(),new ntb);this.a=new ntb;this.k=new ntb;this.j=new ntb;this.b=new ntb;this.n=new ntb;this.f=new ntb;this.e=new ntb}
function r$(a,b){var c,d;if(b.a.R(a)){return}else{d=Wv(rJ(a,(Rib(),hib)),32);c=Wv(yU(a.f,0),7);d==(sN(),$M)?QX(c,pN):d==pN&&QX(c,$M);b.a.db(a,b)}}
function bbb(a){var b,c;c=Plb(1,Wv(rJ(a,(Rib(),Eib)),24).a);a.c.f.g==(CX(),AX)&&a.d.f.g==AX?(b=1):a.c.f.g==AX||a.d.f.g==AX?(b=2):(b=8);return c*b}
function P1(a){var b,c,d,e,f;f=Wv(rJ(a,(Rib(),uib)),7);b=Wv(FU(a.b,xv(dB,gAb,12,a.b.c.length,0,1)),47);for(d=0,e=b.length;d<e;++d){c=b[d];eW(c,f)}}
function Q1(a){var b,c,d,e,f;c=Wv(rJ(a,(Rib(),uib)),7);b=Wv(FU(a.e,xv(dB,gAb,12,a.e.c.length,0,1)),47);for(e=0,f=b.length;e<f;++e){d=b[e];dW(d,c)}}
function Cfb(a){var b,c;yfb(this);c=a.i;b=vI(new HI(c.a,c.b),a.j);this.d=Qlb(c.b,b.b);this.a=Nlb(c.b,b.b);this.b=Qlb(c.a,b.a);this.c=Nlb(c.a,b.a)}
function ipb(a,b,c,d){var e,f,g,h;!d&&(d=(hsb(),hsb(),gsb));e=(f=epb(a,b,c),g=(h=new Array(c-b),Cv(h,a)),dxb(a,b,g,0,f,true),g);jpb(e,a,b,c,-b,d)}
function FU(a,b){var c,d,e;e=a.c.length;b.length<e&&(b=(d=new Array(e),Cv(d,b)));for(c=0;c<e;++c){Av(b,c,a.c[c])}b.length>e&&Av(b,e,null);return b}
function npb(a,b){var c,d,e;e=a.a.length;b.length<e&&(b=(d=new Array(e),Cv(d,b)));for(c=0;c<e;++c){Av(b,c,a.a[c])}b.length>e&&Av(b,e,null);return b}
function xb(a){return ew(a)?a:cw(a)?ilb((Dxb(a),a)):bw(a)?Bkb(Ckb((Dxb(a),a))):_v(a)?a.w():zv(a)?ob(a):a.toString?a.toString():'[JavaScriptObject]'}
function A6(a){var b,c,d,e,f;f=0;for(c=a.b,d=0,e=c.length;d<e;++d){b=c[d];b.g==(CX(),zX)||Umb(a.c,b,Elb(f++));E6(a,b,a.d,(sN(),$M));E6(a,b,a.j,pN)}}
function kbb(){kbb=iI;jbb=new lbb('SIMPLE',0);gbb=new lbb(zAb,1);hbb=new lbb('LINEAR_SEGMENTS',2);fbb=new lbb('BRANDES_KOEPF',3);ibb=new lbb(DAb,4)}
function Xib(){Xib=iI;Wib=new Yib(tzb,0);Sib=new Yib('FIRST',1);Tib=new Yib('FIRST_SEPARATE',2);Uib=new Yib('LAST',3);Vib=new Yib('LAST_SEPARATE',4)}
function Ndb(){Ndb=iI;Mdb=new Vdb;Kdb=TQ(new WQ,(d0(),A_));Ldb=PQ(TQ(new WQ,R_),Q_);Idb=PQ(UQ(TQ(SQ(new WQ,D_),F_),H_),E_);Jdb=PQ(UQ(new WQ,H_),q_)}
function ceb(a){var b,c,d,e;for(c=(e=(new Snb(a.d.a)).a.bb().mb(),new Ynb(e));c.a.G();){b=(d=Wv(c.a.H(),21),Wv(d.yb(),12));vU(b.c.e,b);vU(b.d.b,b)}}
function vvb(a,b){var c,d;vxb(b>0);if((b&-b)==b){return hw(b*wvb(a,31)*4.6566128730773926E-10)}do{c=wvb(a,31);d=c%b}while(c-d+(b-1)<0);return hw(d)}
function zcb(a,b){if(a.c.f==b){return a.d.f}else if(a.d.f==b){return a.c.f}else{throw new slb('Node '+b+' is neither source nor target of edge '+a)}}
function Ekb(a,b,c){vxb(a>=0&&a<=1114111);if(a>=ayb){b[c++]=55296+(a-ayb>>10&1023)&byb;b[c]=56320+(a-ayb&1023)&byb;return 2}else{b[c]=a&byb;return 1}}
function Ol(a,b){Il();var c,d;while(a.G()){if(!b.G()){return false}c=a.H();d=b.H();if(!(gw(c)===gw(d)||c!=null&&rb(c,d))){return false}}return !b.G()}
function JS(a){var b,c,d;Vvb(a.b.a);a.a=xv(kA,syb,25,a.c.b.a.b.c.length,0,1);b=0;for(d=new Tob(a.c.b.a.b);d.a<d.c.c.length;){c=Wv(Rob(d),25);c.k=b++}}
function PT(a){var b,c,d,e;Gpb(a.c,a.a);for(e=new Tob(a.c);e.a<e.c.c.length;){d=Rob(e);for(c=new Tob(a.b);c.a<c.c.c.length;){b=Wv(Rob(c),160);b.Ec(d)}}}
function zW(a){var b,c;if(!a.a){a.a=Do(Wv(a.e,9).c.c.length);for(c=new Tob(Wv(a.e,9).c);c.a<c.c.c.length;){b=Wv(Rob(c),33);vU(a.a,new yW(b))}}return a.a}
function DW(a){var b,c;if(!a.b){a.b=Do(Wv(a.e,7).c.c.length);for(c=new Tob(Wv(a.e,7).c);c.a<c.c.c.length;){b=Wv(Rob(c),33);vU(a.b,new yW(b))}}return a.b}
function F6(a){this.b=a;this.c=(mp(),new ntb);this.i=new ntb;this.d=new ntb;this.j=new ntb;this.k=gw(rJ(hX(a[0]),(eM(),uL)))===gw((NK(),JK));A6(this)}
function sgb(a){switch(a.e){case 1:return 4.71238898038469;default:case 2:return 0;case 3:return 1.5707963267948966;case 4:return 3.141592653589793;}}
function Ql(a){Il();var b;b=Kl(a);if(!Cm(a)){throw new okb('position (0) must be less than the number of elements that remained ('+b+')')}return Dm(a)}
function un(b,c){var d,e;d=b.ub(c);try{e=d.H();d.I();return e}catch(a){a=OH(a);if(aw(a,74)){throw new okb("Can't remove element "+c)}else throw NH(a)}}
function Ye(a,b){var c,d,e,f;f=a.Y();b.length<f&&(b=(e=new Array(f),Cv(e,b)));d=a.mb();for(c=0;c<f;++c){Av(b,c,d.H())}b.length>f&&Av(b,f,null);return b}
function qX(a,b,c){if(!!c&&(b<0||b>c.a.c.length)){throw new slb('index must be >= 0 and <= layer node count')}!!a.d&&BU(a.d.a,a);a.d=c;!!c&&uU(c.a,b,a)}
function Zvb(a,b,c,d,e,f,g,h){var i,j;if(!d){return}i=d.a[0];!!i&&Zvb(a,b,c,i,e,f,g,h);$vb(a,c,d.d,e,f,g,h)&&b.ib(d);j=d.a[1];!!j&&Zvb(a,b,c,j,e,f,g,h)}
function Gxb(a,b,c){if(a<0){throw new okb(jyb+a+' < 0')}if(b>c){throw new okb('toIndex: '+b+' > size '+c)}if(a>b){throw new slb(jyb+a+' > toIndex: '+b)}}
function ee(a,b){var c,d,e;c=b.yb();e=b.zb();d=a.cb(c);if(!(gw(e)===gw(d)||e!=null&&rb(e,d))){return false}if(d==null&&!a.R(c)){return false}return true}
function h1(a,b,c){var d;d=b.c.f;if(d.g==(CX(),zX)){sJ(a,(Rib(),qib),Wv(rJ(d,qib),7));sJ(a,rib,Wv(rJ(d,rib),7))}else{sJ(a,(Rib(),qib),b.c);sJ(a,rib,c.d)}}
function w2(a,b,c){var d;d=b.c.f;if(d.g==(CX(),zX)){sJ(a,(Rib(),qib),Wv(rJ(d,qib),7));sJ(a,rib,Wv(rJ(d,rib),7))}else{sJ(a,(Rib(),qib),b.c);sJ(a,rib,c.d)}}
function at(a,b,c){var d,e,f,g,h;bt(a);for(e=(a.i==null&&(a.i=xv(_F,Txb,46,0,0,1)),a.i),f=0,g=e.length;f<g;++f){d=e[f];at(d,b,'\t'+c)}h=a.e;!!h&&at(h,b,c)}
function yv(a,b){var c=new Array(b);var d;switch(a){case 11:case 12:d=0;break;case 13:d=false;break;default:return c;}for(var e=0;e<b;++e){c[e]=d}return c}
function P5(a){var b,c,d,e;e=xv(qB,Txb,51,a.a.length,0,2);for(c=0;c<e.length;c++){d=a.a[c].length;b=xv(qB,Nzb,9,d,0,1);Gmb(a.a[c],0,b,0,d);e[c]=b}return e}
function AW(a){var b,c;if(!a.b){a.b=Do(Wv(a.e,9).f.c.length);for(c=new Tob(Wv(a.e,9).f);c.a<c.c.c.length;){b=Wv(Rob(c),7);vU(a.b,new FW(b,a.c))}}return a.b}
function sp(b,c){mp();_b(b);try{return ew(c)?Xmb(b,c):Mtb(b.d,c)}catch(a){a=OH(a);if(aw(a,119)){return null}else if(aw(a,76)){return null}else throw NH(a)}}
function Blb(a){var b;b=(Ilb(),Hlb);return b[a>>>28]|b[a>>24&15]<<4|b[a>>20&15]<<8|b[a>>16&15]<<12|b[a>>12&15]<<16|b[a>>8&15]<<20|b[a>>4&15]<<24|b[a&15]<<28}
function ZV(a,b,c){var d,e;if(b.c==(djb(),bjb)&&c.c==ajb){return -1}else if(b.c==ajb&&c.c==bjb){return 1}d=aW(b.a,a.a);e=aW(c.a,a.a);return b.c==bjb?e-d:d-e}
function L7(a){var b,c,d,e,f;e=$xb;f=null;for(d=new Tob(a.d);d.a<d.c.c.length;){c=Wv(Rob(d),89);if(c.c.j^c.d.j){b=c.d.e-c.c.e-c.a;if(b<e){e=b;f=c}}}return f}
function $vb(a,b,c,d,e,f,g){var h,i;if(b.Xc()&&(i=a.a.$b(c,d),i<0||!e&&i==0)){return false}if(b.Yc()&&(h=a.a.$b(c,f),h>0||!g&&h==0)){return false}return true}
function Yj(a){hi();var b,c;if(!a.G()){return kr(),jr}c=a.H();if(!a.G()){return new Gr(c)}b=new Wub;stb(b,_b(c));do{stb(b,_b(a.H()))}while(a.G());return ck(b)}
function m6(a,b,c){a.e=b;a.a=c;a.d=n6(a,(sN(),ZM));a.d+=n6(a,rN);j6(a,b,c,ZM,a.f);j6(a,b,c,rN,a.n);a.b=n6(a,ZM);a.b+=n6(a,rN);j6(a,c,b,ZM,a.f);j6(a,c,b,rN,a.n)}
function hmb(a){var b,c,d;c=(bmb(),a.length);d=0;while(d<c&&a.charCodeAt(d)<=32){++d}b=c;while(b>d&&a.charCodeAt(b-1)<=32){--b}return d>0||b<c?a.substr(d,b-d):a}
function dxb(a,b,c,d,e,f){var g,h,i;if(gw(a)===gw(c)){a=a.slice(b,b+e);b=0}for(h=b,i=b+e;h<i;){g=h+10000<i?h+10000:i;e=g-h;bxb(c,d,f?e:0,a.slice(h,g));h=g;d+=e}}
function Nv(a){var b,c,d;if(Iv(a,(Rv(),Qv))<0){return -Fv((b=~a.l+1&azb,c=~a.m+(b==0?1:0)&azb,d=~a.h+(b==0&&c==0?1:0)&bzb,Ev(b,c,d)))}return a.l+a.m*czb+a.h*dzb}
function JW(a,b){var c;c=a.f;switch(b.e){case 1:return -(a.i.b+a.j.b);case 2:return a.i.a-c.j.a;case 3:return a.i.b-c.j.b;case 4:return -(a.i.a+a.j.a);}return 0}
function KM(){KM=iI;JM=new NM(szb,0);IM=new NM('FREE',1);HM=new NM('FIXED_SIDE',2);EM=new NM('FIXED_ORDER',3);GM=new NM('FIXED_RATIO',4);FM=new NM('FIXED_POS',5)}
function ZT(a,b){var c,d,e,f;c=Wv(rJ(b,(Rib(),fib)),18);f=Wv(Dd(WT,c),18);for(e=f.mb();e.G();){d=Wv(e.H(),18);if(!Wv(Dd(a.a,d),20).V()){return false}}return true}
function HY(a,b,c){this.b=new Dh;this.i=new GU;this.d=new JY(this);this.g=a;this.a=b.c.length;this.c=b;this.e=Wv(yU(this.c,this.c.c.length-1),9);this.f=c;FY(this)}
function Pgb(){Pgb=iI;Lgb=new Rgb('ALWAYS_UP',0);Kgb=new Rgb('ALWAYS_DOWN',1);Ngb=new Rgb('DIRECTION_UP',2);Mgb=new Rgb('DIRECTION_DOWN',3);Ogb=new Rgb('SMART',4)}
function Iv(a,b){var c,d,e,f,g,h,i,j;i=a.h>>19;j=b.h>>19;if(i!=j){return j-i}e=a.h;h=b.h;if(e!=h){return e-h}d=a.m;g=b.m;if(d!=g){return d-g}c=a.l;f=b.l;return c-f}
function K7(a){var b,c,d,e;for(c=(e=(new Snb(a.p.a)).a.bb().mb(),new Ynb(e));c.a.G();){b=(d=Wv(c.a.H(),21),Wv(d.yb(),89));if(b.e&&a.b[b.b]<0){return b}}return null}
function TN(a,b){var c,d,e,f,g;d=Qlb(a.d,b.d);f=Qlb(a.e,b.e);e=Nlb(a.d+a.c,b.d+b.c);g=Nlb(a.e+a.b,b.e+b.b);if(e<d){c=d;d=e;e=c}if(g<f){c=f;f=g;g=c}SN(a,d,f,e-d,g-f)}
function hQ(a,b){var c;if(Gzb in a.a){c=Pu(a,Gzb);if(!c.kc()){throw new GQ("The 'properties' property of a graph element must be an object.",c,a)}iQ(c.kc(),b,true)}}
function HS(a,b){var c,d,e;d=a.b.j.e;a.a||(d+=a.b.j.b);e=b.b.j.e;b.a||(e+=b.b.j.b);c=glb(d,e);if(c==0){if(!a.a&&b.a){return -1}else if(!b.a&&a.a){return 1}}return c}
function kX(a){var b,c;switch(Wv(rJ(hX(a),(Mjb(),ujb)),174).e){case 0:b=a.i;c=a.j;return new HI(b.a+c.a/2,b.b+c.b/2);case 1:return new II(a.i);default:return null;}}
function RX(){LX();cX.call(this);this.g=(sN(),qN);this.a=new FI;this.d=new ZW;this.c=(Mh(2,Vyb),new HU(2));this.b=(Mh(4,Vyb),new HU(4));this.e=(Mh(4,Vyb),new HU(4))}
function G6(a,b,c){a.d=0;a.b=0;P6(a,b,c);b.g==(CX(),BX)&&c.g==zX?M6(b).g==(sN(),$M)?(a.d=1):(a.b=1):c.g==BX&&b.g==zX&&(M6(c).g==(sN(),$M)?(a.b=1):(a.d=1));O6(a,b,c)}
function h9(a,b){var c,d;for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),9);a.a[c.d.k][c.k].a=uvb(a.e);a.a[c.d.k][c.k].d=Ixb(a.a[c.d.k][c.k].a);a.a[c.d.k][c.k].b=1}}
function d9(a,b,c){var d,e,f;for(f=new Tob(b);f.a<f.c.c.length;){d=Wv(Rob(f),9);a.a[d.d.k][d.k].e=false}for(e=new Tob(b);e.a<e.c.c.length;){d=Wv(Rob(e),9);c9(a,d,c)}}
function Ydb(a,b){var c,d,e,f;c=0;d=0;for(f=new Tob(b.b);f.a<f.c.c.length;){e=Wv(Rob(f),33);c=Nlb(c,e.j.a);d+=e.j.b}sJ(b,(Rib(),Lib),new HI(c,d));a.k<c&&(a.k=c);a.j+=d}
function Vbb(a,b){this.c=(mp(),new ntb);this.a=a;this.b=b;this.d=Wv(rJ(a,(Rib(),Kib)),134);gw(rJ(a,(Mjb(),hjb)))===gw((lcb(),kcb))?(this.e=new Jcb):(this.e=new Ccb)}
function Z4(a,b){var c,d,e,f;e=0;for(d=0;d<b.length;d++){c=b[d];if(d<b.length-1){f=b[d+1];e+=$4(a,c,f)}e+=(a.d=new F6(c),x6(a.d));e+=(a.a=new k6(c),a6(a.a))}return e}
function S6(a){switch(a.c.e){case 1:return LX(),HX;case 2:return LX(),FX;case 3:return LX(),JX;case 4:return LX(),KX;}throw new Imb("Can't filter on undefined side")}
function Pr(b,c){var d;try{d=b.c.a;if(!ok(b.b,c)||!d){return 0}return Es(d,b.d,c)}catch(a){a=OH(a);if(aw(a,119)){return 0}else if(aw(a,76)){return 0}else throw NH(a)}}
function J4(a){var b,c,d,e,f;for(d=new rnb((new inb(a.b)).a);d.b;){c=pnb(d);b=Wv(c.yb(),9);f=Wv(Wv(c.zb(),27).a,9);e=Wv(Wv(c.zb(),27).b,10);vI(BI(b.i),vI(xI(f.i),e))}}
function B9(a,b,c){var d,e,f;d=glb(a.a[b.k],a.a[c.k]);if(d==0){e=Wv(rJ(b,(Rib(),oib)),20);f=Wv(rJ(c,oib),20);if(e.kb(c)){return -1}else if(f.kb(b)){return 1}}return d}
function ogb(a,b){var c,d;d=vI(xI(a.i),a.a);c=a.f.j;switch(b.e){case 1:return -d.b;case 2:return -d.a+c.a;case 3:return -d.b+c.b;case 4:return -d.a;default:return 0;}}
function Z8(a,b){var c,d,e,f;for(e=0;e<b.length;e++){e+1<b.length&&X8(a,b[e+1],(djb(),ajb));f=b[e];c=0;for(d=0;d<f.length;d++){Y8(a,f[d]);c+=a.Hc(f[d],c,(djb(),bjb))}}}
function Mfb(){Mfb=iI;Lfb=UQ(UQ(RQ(new WQ,(d0(),__)),$_),a0);Hfb=PQ(UQ(TQ(SQ(new WQ,D_),F_),H_),E_);Jfb=TQ(new WQ,A_);Kfb=PQ(TQ(new WQ,R_),Q_);Ifb=PQ(UQ(new WQ,H_),q_)}
function dI(b,c,d,e){cI();var f=aI;$moduleName=c;$moduleBase=d;LH=e;function g(){for(var a=0;a<f.length;a++){f[a]()}}
if(b){try{Rxb(g)()}catch(a){b(c,a)}}else{Rxb(g)()}}
function clb(a){blb==null&&(blb=/^\s*[+-]?(NaN|Infinity|((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+)?[dDfF]?)\s*$/);if(!elb(blb,a)){throw new Ylb(dyb+a+'"')}return parseFloat(a)}
function _gb(){_gb=iI;Ygb=new ahb(tzb,0);Xgb=new ahb('LEFTUP',1);$gb=new ahb('RIGHTUP',2);Wgb=new ahb('LEFTDOWN',3);Zgb=new ahb('RIGHTDOWN',4);Vgb=new ahb('BALANCED',5)}
function zgb(){zgb=iI;ygb=new Agb('V_TOP',0);xgb=new Agb('V_CENTER',1);wgb=new Agb('V_BOTTOM',2);ugb=new Agb('H_LEFT',3);tgb=new Agb('H_CENTER',4);vgb=new Agb('H_RIGHT',5)}
function YK(){YK=iI;WK=new ZK(tzb,0);UK=new ZK('DIRECTED',1);XK=new ZK('UNDIRECTED',2);SK=new ZK('ASSOCIATION',3);VK=new ZK('GENERALIZATION',4);TK=new ZK('DEPENDENCY',5)}
function CX(){CX=iI;AX=new DX('NORMAL',0);zX=new DX('LONG_EDGE',1);xX=new DX('EXTERNAL_PORT',2);BX=new DX('NORTH_SOUTH_PORT',3);yX=new DX('LABEL',4);wX=new DX('BIG_NODE',5)}
function wv(a,b,c,d,e,f,g){var h,i,j,k,l;k=e[f];j=f==g-1;h=j?d:0;l=yv(h,k);d!=9&&Bv(tv(a,g-f),b[f],c[f],h,l);if(!j){++f;for(i=0;i<k;++i){l[i]=wv(a,b,c,d,e,f,g)}}return l}
function gX(a){var b,c,d;b=new GU;for(d=new Tob(a.f);d.a<d.c.c.length;){c=Wv(Rob(d),7);vU(b,Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[c.b,c.e]))))))}return _b(b),new Vh(b)}
function b7(a,b,c){this.a=c;if(a>=b.length){throw new okb('Greedy SwitchDecider: Free layer layer not in graph.')}this.b=b[a];this.c=new r6(this.b);this.d=new R6(this.b)}
function _n(a,b){var c;this.f=a;this.b=this.f.c;c=a.d;bc(b,c);if(b>=(c/2|0)){this.e=a.e;this.d=c;while(b++<c){Zn(this)}}else{this.c=a.a;while(b-->0){Yn(this)}}this.a=null}
function qS(a){var b,c,d;for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);d=b.j.d;b.j.d=b.j.e;b.j.e=d;d=b.j.c;b.j.c=b.j.b;b.j.b=d;d=b.g.a;b.g.a=b.g.b;b.g.b=d}fS(a)}
function f1(a,b){var c,d,e;d=new Fnb(a.b,0);while(d.b<d.d.Y()){c=(Bxb(d.b<d.d.Y()),Wv(d.d.sb(d.c=d.b++),33));e=Wv(rJ(c,(eM(),tL)),107);if(e==(EK(),BK)){vnb(d);vU(b.b,c)}}}
function Vab(a,b,c){var d,e,f,g;g=zU(a.f,b,0);f=new Wab;f.b=c;d=new Fnb(a.f,g);while(d.b<d.d.Y()){e=(Bxb(d.b<d.d.Y()),Wv(d.d.sb(d.c=d.b++),9));e.k=c;vU(f.f,e);vnb(d)}return f}
function Eq(a,b){Dq();var c,d,e;if(b.V()){return false}if(aw(b,207)){e=Wv(b,207);for(d=e.bb().mb();d.G();){c=Wv(d.H(),83);a.Bb(c.Zb(),c.Yb())}}else{Jl(a,b.mb())}return true}
function MN(){MN=iI;KN=new NN('DEFAULT_MINIMUM_SIZE',0);LN=new NN('MINIMUM_SIZE_ACCOUNTS_FOR_INSETS',1);JN=new NN('COMPUTE_INSETS',2);IN=new NN('APPLY_ADDITIONAL_INSETS',3)}
function MP(a){var b,c,d,e;c=a.a.b+2;e=xv(qz,Fzb,10,c,0,1);e[0]=xI(MX(a.c));d=WI(a.a,0);while(d.b!=d.d.c){b=Wv(_ub(d),10);e[d.a]=new HI(b.a,b.b)}e[c-1]=xI(MX(a.d));return e}
function ge(a,b,c){var d,e,f;for(e=a.bb().mb();e.G();){d=Wv(e.H(),21);f=d.yb();if(gw(b)===gw(f)||b!=null&&rb(b,f)){if(c){d=new qob(d.yb(),d.zb());e.I()}return d}}return null}
function f9(a,b,c){var d,e;d=a.a[b.d.k][b.k];e=a.a[c.d.k][c.k];if(d.a!=null&&e.a!=null){return flb(d.a,e.a)}else if(d.a!=null){return -1}else if(e.a!=null){return 1}return 0}
function beb(a,b,c){var d,e,f;e=b.c;f=b.d;d=c;if(stb(a.a,b)){Xdb(a,e)&&(d=true);Xdb(a,f)&&(d=true);if(d){BU(b.c.e,b);BU(b.d.b,b);stb(a.d,b)}Ydb(a,b);return true}return false}
function $eb(a,b,c){var d,e;e=Zeb(a,b);if(e==a.c){return Web(a,Yeb(a,b))}if(c){_eb(a,b,a.c-e);return Web(a,Yeb(a,b))}else{d=new dfb(a);_eb(d,b,a.c-e);return Web(d,Yeb(d,b))}}
function $tb(){function b(){try{return (new Map).entries().next().done}catch(a){return false}}
if(typeof Map===Zxb&&Map.prototype.entries&&b()){return Map}else{return _tb()}}
function Dd(a,b){var c;c=Wv(Smb(a.b,b),19);!c&&(c=a.Z());return aw(c,137)?new Lg(a,b,Wv(c,137)):aw(c,18)?new Kg(a,b,Wv(c,18)):aw(c,20)?Ld(a,b,Wv(c,20),null):new _f(a,b,c,null)}
function Gs(a){switch(Rs(a.e)-Rs(a.g)){case -2:Cs(a.g)>0&&(a.g=Ls(a.g));return Ks(a);case 2:Cs(a.e)<0&&(a.e=Ks(a.e));return Ls(a);default:a.d=1+Plb(Rs(a.e),Rs(a.g));return a;}}
function k5(a,b){this.f=(mp(),new ntb);this.b=new ntb;this.j=new ntb;this.a=a;this.c=b;this.c>0&&j5(this,this.c-1,(sN(),ZM));this.c<this.a.length-1&&j5(this,this.c+1,(sN(),rN))}
function jt(a){var b;if(a.c==null){b=gw(a.b)===gw(ht)?null:a.b;a.d=b==null?Wxb:dw(b)?mt(Zv(b)):ew(b)?'String':Ikb(tb(b));a.a=a.a+': '+(dw(b)?lt(Zv(b)):b+'');a.c='('+a.d+') '+a.a}}
function IY(a){var b,c,d,e;for(c=new Tob(a.a.c);c.a<c.c.c.length;){b=Wv(Rob(c),9);for(e=WI(Eo(b.c),0);e.b!=e.d.c;){d=Wv(_ub(e),33);rJ(d,(Rib(),uib))==null&&BU(b.c,d)}}return null}
function e3(a,b){var c,d,e,f,g;g=new GU;for(d=Wv(qsb(a3,a),20).mb();d.G();){c=Wv(d.H(),75);xU(g,c.b)}Dpb(g);K2(g,a.a);for(f=new Tob(g);f.a<f.c.c.length;){e=Wv(Rob(f),7);Anb(b,e)}}
function P7(a){var b,c,d,e;while(a.o.a.c.length!=0){c=Wv(Svb(a.o),27);d=Wv(c.a,61);b=Wv(c.b,89);e=c7(b,d);if(b.d==d){o7(e.g,b);d.e=e.e+b.a}else{o7(e.c,b);d.e=e.e-b.a}vU(a.e.a,d)}}
function Tr(a,b,c){var d,e,f;Mh(c,'count');if(!ok(a.b,b)){Xb(c==0);return 0}f=a.c.a;if(!f){c>0&&Lr(a,b,c);return 0}e=xv(mw,Yyb,26,1,12,1);d=Ns(f,a.d,b,c,e);Us(a.c,f,d);return e[0]}
function l$(a,b){var c,d,e,f,g;e=Wv(rJ(b,(Rib(),Jib)),15).a*Wv(rJ(b,(Mjb(),qjb)),15).a;g=a[0].i.a+a[0].j.a;for(f=1;f<a.length;f++){c=a[f].i;d=a[f].j;c.a<=g+e&&(c.a=g+e);g=c.a+d.a}}
function tvb(){tvb=iI;var a,b,c,d;qvb=xv(kw,hyb,26,25,12,1);rvb=xv(kw,hyb,26,33,12,1);d=1.52587890625E-5;for(b=32;b>=0;b--){rvb[b]=d;d*=0.5}c=1;for(a=24;a>=0;a--){qvb[a]=c;c*=0.5}}
function f5(a){while(a.g.c!=0&&a.d.c!=0){if(o5(a.g).c>o5(a.d).c){a.i+=a.g.c;q5(a.d)}else if(o5(a.d).c>o5(a.g).c){a.e+=a.d.c;q5(a.g)}else{a.i+=n5(a.g);a.e+=n5(a.d);q5(a.g);q5(a.d)}}}
function TP(a){if(!a){throw new EQ('An element is null. The origin of an edge could not be determined, this might be due to an inconsistency within the internal element mappings.')}}
function UP(a,b){var c,d;Ymb(a.i);Ymb(a.a);Ymb(a.k);Ymb(a.j);Ymb(a.b);Ymb(a.n);Ymb(a.f);Ymb(a.e);if(a.d){d=Pu(a.d,OP.b);!!d&&!!d.ic()&&(a.c=d.ic().a)}c=fQ(a,b,null);bQ(a,b);return c}
function kfb(a){var b,c,d,e,f,g;d=hfb(gfb(a));b=rAb;f=0;e=0;while(b>0.5&&f<50){e=ofb(d);c=$eb(d,e,true);b=Jlb(c.b);++f}g=Yv(tn(Eo(a.g),Eo(a.g).b-1));return $eb(a,(Dxb(g),g)-e,false)}
function lfb(a){var b,c,d,e,f,g;d=hfb(gfb(a));b=rAb;f=0;e=0;while(b>0.5&&f<50){e=nfb(d);c=$eb(d,e,true);b=Jlb(c.a);++f}g=Yv(tn(Eo(a.g),Eo(a.g).b-1));return $eb(a,(Dxb(g),g)-e,false)}
function Ze(a){var b,c,d,e;e=new Bmb('[');b=false;for(d=a.mb();d.G();){c=d.H();b?(e.a+=', ',e):(b=true);ymb(e,c===a?'(this Collection)':(bmb(),c==null?Wxb:xb(c)))}e.a+=']';return e.a}
function ie(a){var b,c,d,e;e=new Bmb('{');b=false;for(d=a.bb().mb();d.G();){c=Wv(d.H(),21);b?(e.a+=', ',e):(b=true);ymb(e,je(a,c.yb()));e.a+='=';ymb(e,je(a,c.zb()))}e.a+='}';return e.a}
function Ks(a){var b;dc(!!a.g);b=a.g;a.g=b.e;b.e=a;b.j=a.j;b.a=a.a;a.a=1+Zr(a.e)+Zr(a.g);a.j=PH(PH(a.c,Ts(a.e)),Ts(a.g));a.d=1+Plb(Rs(a.e),Rs(a.g));b.d=1+Plb(Rs(b.e),Rs(b.g));return b}
function Ls(a){var b;dc(!!a.e);b=a.e;a.e=b.g;b.g=a;b.j=a.j;b.a=a.a;a.a=1+Zr(a.e)+Zr(a.g);a.j=PH(PH(a.c,Ts(a.e)),Ts(a.g));a.d=1+Plb(Rs(a.e),Rs(a.g));b.d=1+Plb(Rs(b.e),Rs(b.g));return b}
function ZO(a){var b;if(!Qob(new Tob(AW(a.e)))){return}b=Wv(oW(a.e,(eM(),TL)),28);b==(KM(),FM)?SO(a.e):b==GM?TO(a.e):Ckb(Ixb(Xv(oW(a.e,AL))))||a.e.e.j.a==0&&a.e.e.j.b==0?UO(a.e):WO(a)}
function s3(a,b,c){var d,e,f;e=new Tob(a);if(e.a<e.c.c.length){f=Wv(Rob(e),33);d=r3(f,b,c);while(e.a<e.c.c.length){f=Wv(Rob(e),33);Afb(d,r3(f,b,c))}return new Dfb(d)}else{return null}}
function u2(a,b){var c,d,e,f,g,h;e=0;for(d=new Tob(b.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);for(g=new Tob(c.a);g.a<g.c.c.length;){f=Wv(Rob(g),9);h=f.j.a+f.e.c+f.e.b+a.b;e=e>h?e:h}}return e}
function sT(a,b){oT();var c;if(a.c==b.c){if(a.b==b.b||gT(a.b,b.b)){c=dT(a.b)?1:-1;if(a.a&&!b.a){return c}else if(!a.a&&b.a){return -c}}return xlb(a.b.e,b.b.e)}else{return glb(a.c,b.c)}}
function nU(a){var b,c;c=xI(MI(Bv(tv(qz,1),Fzb,10,0,[a.f.i,a.i,a.a])));b=a.f.e;switch(a.g.e){case 1:c.b-=b.d;break;case 2:c.a+=b.c;break;case 3:c.b+=b.a;break;case 4:c.a-=b.b;}return c}
function z6(a,b){var c;c=0;if(b.g==(CX(),BX)){if(C6(b).f!=a.a){D6(a,C6(b).f);a.e=true}a.e?++a.g:(c+=a.f)}else if(b.g==zX){a.e?(c+=a.g):++a.f}else if(b.g==AX){D6(a,b);a.e=false}return c}
function HV(a,b,c,d,e){var f,g,h,i;i=null;for(h=new Tob(d);h.a<h.c.c.length;){g=Wv(Rob(h),187);if(g!=c&&zU(g.e,e,0)!=-1){i=g;break}}f=IV(e);dW(f,c.b);eW(f,i.b);Fd(a.a,e,new XV(f,b,c.f))}
function FZ(a){switch(Wv(rJ(a,(Mjb(),vjb)),85).e){case 1:sJ(a,vjb,(Xib(),Uib));break;case 2:sJ(a,vjb,(Xib(),Vib));break;case 3:sJ(a,vjb,(Xib(),Sib));break;case 4:sJ(a,vjb,(Xib(),Tib));}}
function iQ(a,b,c){var d,e,f,g;if(a){for(e=(f=Nu(a,xv($F,Txb,2,0,5,1)),new wnb(new opb((new _u(a,f)).b)));e.b<e.d.Y();){d=(Bxb(e.b<e.d.Y()),$v(e.d.sb(e.c=e.b++)));g=Pu(a,d);wQ(b,d,g,c)}}}
function G5(a,b,c){var d,e,f,g,h,i;e=1;while(e<a){e*=2}i=2*e-1;e-=1;h=xv(mw,Yyb,26,i,12,1);d=0;for(g=0;g<b;g++){f=c[g]+e;++h[f];while(f>0){f%2>0&&(d+=h[f+1]);f=(f-1)/2|0;++h[f]}}return d}
function aeb(a,b,c){var d,e,f,g;a.e=b;if(c){for(e=(g=(new Snb(a.a.a)).a.bb().mb(),new Ynb(g));e.a.G();){d=(f=Wv(e.a.H(),21),Wv(f.yb(),12));sJ(d,(Rib(),Mib),a.e);QX(d.c,b.a);QX(d.d,b.b)}}}
function g4(){g4=iI;e4=new h4(tzb,0);b4=new h4(ozb,1);f4=new h4(pzb,2);d4=new h4('LEFT_RIGHT_CONSTRAINT_LOCKING',3);c4=new h4('LEFT_RIGHT_CONNECTION_LOCKING',4);a4=new h4('EDGE_LENGTH',5)}
function N5(a,b,c,d){var e;this.b=d;this.e=a.a;e=b[c];this.d=vv(KH,[Txb,xAb],[227,26],13,[e.length,e.length],2);this.a=vv(mw,[Txb,Yyb],[52,26],12,[e.length,e.length],2);this.c=new k5(b,c)}
function fwb(a,b,c,d){var e,f;f=b;e=f.d==null||a.a.$b(c.d,f.d)>0?1:0;while(f.a[e]!=c){f=f.a[e];e=a.a.$b(c.d,f.d)>0?1:0}f.a[e]=d;d.b=c.b;d.a[0]=c.a[0];d.a[1]=c.a[1];c.a[0]=null;c.a[1]=null}
function ZQ(a,b,c){var d,e,f,g;nI(c,Tzb,1);NQ(a.d,b);g=sV(a.a,b);if(g.Y()==1){_Q(Wv(g.sb(0),55),c)}else{f=1/g.Y();for(e=g.mb();e.G();){d=Wv(e.H(),55);_Q(d,rI(c,f))}}qV(a.a,g,b);bR(b);pI(c)}
function o6(a,b,c){var d,e,f,g,h;h=new U6(b,c);for(g=T6(h);g.G();){f=Wv(g.H(),7);for(e=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[f.b,f.e]))))));Cm(e);){d=Wv(Dm(e),12);bW(d)||l6(a,b,f,d)}}}
function _6(a,b){var c,d,e;e=nX(a,b);for(d=e.mb();d.G();){c=Wv(d.H(),7);if(rJ(c,(Rib(),Bib))!=null||Cm(Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[c.b,c.e])))))))){return true}}return false}
function Efb(a){var b,c;if(sl(a)){throw new slb(TAb)}for(c=WI(a,0);c.b!=c.d.c;){b=Wv(_ub(c),10);this.d=Qlb(this.d,b.b);this.c=Nlb(this.c,b.a);this.a=Nlb(this.a,b.b);this.b=Qlb(this.b,b.a)}}
function wI(a,b,c){if(b<0||c<0){throw new slb('The highx must be bigger then lowx and the highy must be bigger then lowy')}a.a<0?(a.a=0):a.a>b&&(a.a=b);a.b<0?(a.b=0):a.b>c&&(a.b=c);return a}
function nX(a,b){switch(b.e){case 1:return pl(a.f,(LX(),HX));case 2:return pl(a.f,(LX(),FX));case 3:return pl(a.f,(LX(),JX));case 4:return pl(a.f,(LX(),KX));default:return ypb(),ypb(),vpb;}}
function K0(a){var b,c,d,e;for(e=(Il(),new Im(Dl(ul(a.a,new yl))));Cm(e);){d=Wv(Dm(e),9);d.g==(CX(),yX)&&sJ(d,(Rib(),pib),(kP(),hP));for(c=Uh(mX(d));Cm(c);){b=Wv(Dm(c),12);M0(b,(kP(),hP))}}}
function L0(a){var b,c,d,e;for(e=(Il(),new Im(Dl(ul(a.a,new yl))));Cm(e);){d=Wv(Dm(e),9);d.g==(CX(),yX)&&sJ(d,(Rib(),pib),(kP(),gP));for(c=Uh(mX(d));Cm(c);){b=Wv(Dm(c),12);M0(b,(kP(),gP))}}}
function cdb(a,b){this.b=new vtb;switch(a){case 0:this.d=new Ddb(this);break;case 1:this.d=new tdb(this);break;case 2:this.d=new ydb(this);break;default:throw new rlb;}this.c=b;this.a=0.2*b}
function uW(a){var b,c,d,e;if(!a.b){a.b=new GU;for(c=new Tob(a.a.c);c.a<c.c.c.length;){b=Wv(Rob(c),16);for(e=new Tob(b.a);e.a<e.c.c.length;){d=Wv(Rob(e),9);vU(a.b,new BW(d,a.c))}}}return a.b}
function l5(a,b){var c,d,e;c=m5(b,a.e);d=Wv(Smb(a.g.f,c),24).a;e=a.a.c.length-1;if(a.a.c.length!=0&&Wv(yU(a.a,e),128).c==d){++Wv(yU(a.a,e),128).a;++Wv(yU(a.a,e),128).b}else{vU(a.a,new v5(d))}}
function lmb(a){bmb();var b,c;if(a>=ayb){b=55296+(a-ayb>>10&1023)&byb;c=56320+(a-ayb&1023)&byb;return String.fromCharCode(b)+(''+String.fromCharCode(c))}else{return String.fromCharCode(a&byb)}}
function KV(a,b,c,d){var e,f,g;e=hX(c);f=PW(e);g=new RX;PX(g,c);switch(d.e){case 1:QX(g,tN(vN(f)));break;case 2:QX(g,vN(f));}sJ(g,(Rib(),tib),Wv(rJ(b,tib),15));sJ(b,uib,g);Umb(a.b,g,b);return g}
function l6(a,b,c,d){var e;vU(a.c,new t6(a,c,d,Wv(Smb(a.k,c),24).a));if(d6(d)&&(b==a.e?d.d.f!=a.a&&d.c.f!=a.a:d.d.f!=a.e&&d.c.f!=a.e)){e=c==d.c?d.d:d.c;vU(a.c,new t6(a,e,d,Wv(Smb(a.k,e),24).a))}}
function fe(a,b){var c,d,e;if(b===a){return true}if(!aw(b,57)){return false}e=Wv(b,57);if(a.Y()!=e.Y()){return false}for(d=e.bb().mb();d.G();){c=Wv(d.H(),21);if(!a._(c)){return false}}return true}
function $Z(a,b){var c,d,e;d=new uX(a);qJ(d,b);sJ(d,(Rib(),gib),b);sJ(d,(eM(),TL),(KM(),FM));sJ(d,lL,(iK(),eK));sX(d,(CX(),xX));c=new RX;PX(c,d);QX(c,(sN(),rN));e=new RX;PX(e,d);QX(e,ZM);return d}
function O7(a,b){var c,d,e;e=$xb;for(d=new Tob(m7(b));d.a<d.c.c.length;){c=Wv(Rob(d),89);if(c.e&&!a.c[c.b]){a.c[c.b]=true;e=Slb(e,O7(a,c7(c,b)))}}a.i[b.b]=a.j;a.g[b.b]=Slb(e,a.j++);return a.g[b.b]}
function _eb(a,b,c){var d,e,f,g;g=a.g.tb();if(a.e){for(e=0;e<a.c;e++){g.H()}}else{for(e=0;e<a.c-1;e++){g.H()}}f=a.b.tb();d=Ixb(Yv(g.H()));while(d-b<RAb){d=Ixb(Yv(g.H()));f.H()}g.M();afb(a,c,b,f,g)}
function Lt(b,c){var d,e,f,g;for(e=0,f=b.length;e<f;e++){g=b[e];try{g[1]?g[0].bd()&&(c=Kt(c,g)):g[0].bd()}catch(a){a=OH(a);if(aw(a,46)){d=a;Ct(aw(d,164)?Wv(d,164).cc():d)}else throw NH(a)}}return c}
function Qr(a){var b,c,d;d=a.c.a;if(!d){return null}if(a.b.b){b=a.b.e;c=Ds(a.c.a,a.d,b);if(!c){return null}a.b.d==(Gh(),Fh)&&a.d.$b(b,c.b)==0&&(c=c.i)}else{c=a.a.i}return c==a.a||!ok(a.b,c.b)?null:c}
function t2(a,b){var c,d,e,f,g,h;f=0;for(d=new Tob(b.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);e=0;for(h=new Tob(c.a);h.a<h.c.c.length;){g=Wv(Rob(h),9);e+=g.j.b+g.e.a+g.e.d+a.a}e-=a.a;f=f>e?f:e}return f}
function M7(a){var b,c,d,e,f;f=$xb;e=$xb;for(d=new Tob(m7(a));d.a<d.c.c.length;){c=Wv(Rob(d),89);b=c.d.e-c.c.e;c.d==a&&b<e?(e=b):b<f&&(f=b)}e==$xb&&(e=-1);f==$xb&&(f=-1);return new RJ(Elb(e),Elb(f))}
function l8(a,b,c){var d,e,f,g,h;b.k=-1;for(h=oX(b,(djb(),bjb)).mb();h.G();){g=Wv(h.H(),7);for(e=new Tob(g.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);f=d.d.f;b!=f&&(f.k<0?c.ib(d):f.k>0&&l8(a,f,c))}}b.k=0}
function Bfb(a,b){yfb(this);if(0>b){throw new slb('Top must be smaller or equal to bottom.')}else if(0>a){throw new slb('Left must be smaller or equal to right.')}this.d=0;this.c=a;this.a=b;this.b=0}
function Ffb(a){var b,c,d;yfb(this);if(a.length==0){throw new slb(TAb)}for(c=0,d=a.length;c<d;++c){b=a[c];this.d=Qlb(this.d,b.b);this.c=Nlb(this.c,b.a);this.a=Nlb(this.a,b.b);this.b=Qlb(this.b,b.a)}}
function g0(){d0();return Bv(tv(mC,1),uyb,37,0,[L_,o_,c0,m_,p_,__,z_,T_,j_,D_,S_,P_,I_,s_,h_,N_,W_,F_,G_,A_,Z_,V_,R_,r_,U_,$_,Y_,B_,x_,H_,k_,C_,a0,O_,t_,v_,J_,i_,l_,y_,u_,M_,Q_,E_,w_,X_,K_,n_,b0,q_])}
function a5(a,b){var c,d,e,f,g,h,i,j,k;k=0;for(d=0,e=b.length;d<e;++d){c=b[d];for(g=0,h=c.length;g<h;++g){f=c[g];for(j=new Tob(f.f);j.a<j.c.c.length;){i=Wv(Rob(j),7);i.k=k++}}}a.a=xv(mw,Yyb,26,k,12,1)}
function Sl(a){Il();var b,c,d;b=a.H();if(!a.G()){return b}d=new zmb;d.a+='expected one element but was: <'+b;for(c=0;c<4&&a.G();c++){ymb(d,', '+a.H())}a.G()&&(d.a+=', ...',d);d.a+='>';throw new slb(d.a)}
function x6(a){var b,c,d,e,f;b=0;for(d=a.b,e=0,f=d.length;e<f;++e){c=d[e];b+=z6(a,c);if(LM(Wv(rJ(c,(eM(),TL)),28))){nX(c,(sN(),$M)).mb().G()&&(b+=y6(a,c,$M));nX(c,pN).mb().G()&&(b+=y6(a,c,pN))}}return b}
function i5(a,b,c,d){var e,f,g,h,i;if(d.d.c+d.e.c==0){for(g=a.a[a.c],h=0,i=g.length;h<i;++h){f=g[h];Umb(d,f,new r5(a,f,c))}}e=Wv(re(Ktb(d.d,b)),284);e.b=0;e.c=e.f;e.c==0||u5(Wv(yU(e.a,e.b),128));return e}
function Dpb(a){var h;ypb();var b,c,d,e,f,g;if(aw(a,63)){for(e=0,d=a.Y()-1;e<d;++e,--d){h=a.sb(e);a.wb(e,a.sb(d));a.wb(d,h)}}else{b=a.tb();f=a.ub(a.Y());while(b.L()<f.N()){c=b.H();g=f.M();b.O(g);f.O(c)}}}
function Wb(a,b,c){if(a<0||a>c){return Vb(a,c,'start index')}if(b<0||b>c){return Vb(b,c,'end index')}return fc('end index (%s) must not be less than start index (%s)',Bv(tv(UF,1),syb,1,4,[Elb(b),Elb(a)]))}
function SP(a){if(!('id' in a.a)){throw new FQ("Every graph element must specify an 'id' property.",a)}if(!Pu(a,'id').lc()){throw new FQ("Invalid format for 'id'. Must be a string, was "+Pu(a,'id').$c,a)}}
function f3(a,b){var c,d,e,f,g,h,i;i=a.b;for(d=Wv(qsb(a3,a),20).mb();d.G();){c=Wv(d.H(),75);for(h=(f=(new Snb(c.c.a)).a.bb().mb(),new Ynb(f));h.a.G();){g=(e=Wv(h.a.H(),21),Wv(e.yb(),7));Anb(b,g);J2(g,i)}}}
function _db(a,b){var c,d,e;for(e=new Tob(b.e);e.a<e.c.c.length;){c=Wv(Rob(e),12);if(c.d.f!=a.f){return true}}for(d=new Tob(b.b);d.a<d.c.c.length;){c=Wv(Rob(d),12);if(c.c.f!=a.f){return true}}return false}
function Z2(a){var b,c,d,e;We(a.c);We(a.b);We(a.a);for(e=(c=(new Snb(a.e)).a.bb().mb(),new Ynb(c));e.a.G();){d=(b=Wv(e.a.H(),21),Wv(b.yb(),60));if(d.c!=2){Wsb(a.a,d);d.c==0&&Wsb(a.c,d)}Wsb(a.b,d)}a.d=false}
function mr(b,c){var d;if(b===c){return true}if(aw(c,18)){d=Wv(c,18);try{return b.Y()==d.Y()&&b.lb(d)}catch(a){a=OH(a);if(aw(a,76)){return false}else if(aw(a,119)){return false}else throw NH(a)}}return false}
function Ltb(a,b,c){var d,e,f,g;g=b==null?0:a.b.Vc(b);e=(d=Ttb(a.a,g),d==null?[]:d);if(e.length==0){Vtb(a.a,g,e)}else{f=Itb(a,b,e);if(f){return f.Ab(c)}}Av(e,e.length,new qob(b,c));++a.c;msb(a.b);return null}
function Vb(a,b,c){if(a<0){return fc(ryb,Bv(tv(UF,1),syb,1,4,[c,Elb(a)]))}else if(b<0){throw new slb(tyb+b)}else{return fc('%s (%s) must not be greater than size (%s)',Bv(tv(UF,1),syb,1,4,[c,Elb(a),Elb(b)]))}}
function Ub(a,b){if(a<0){return fc(ryb,Bv(tv(UF,1),syb,1,4,['index',Elb(a)]))}else if(b<0){throw new slb(tyb+b)}else{return fc('%s (%s) must be less than size (%s)',Bv(tv(UF,1),syb,1,4,['index',Elb(a),Elb(b)]))}}
function jW(a){var b,c,d,e;e=xv(qB,Txb,51,a.c.c.length,0,2);d=new Fnb(a.c,0);while(d.b<d.d.Y()){b=(Bxb(d.b<d.d.Y()),Wv(d.d.sb(d.c=d.b++),16));c=d.b-1;e[c]=Wv(FU(b.a,xv(qB,Nzb,9,b.a.c.length,0,1)),51)}return e}
function w3(a,b,c,d,e){this.c=e;this.d=b;this.a=c;switch(e.e){case 4:this.b=Jlb(a.b);break;case 1:this.b=Jlb(a.d);break;case 2:this.b=Jlb(a.c-d.j.a);break;case 3:this.b=Jlb(a.a-d.j.b);break;default:this.b=0;}}
function adb(a,b,c,d,e){var f,g,h,i,j;if(b){for(h=b.mb();h.G();){g=Wv(h.H(),9);for(j=pX(g,(djb(),bjb),c).mb();j.G();){i=Wv(j.H(),7);f=Wv(re(Ktb(e.d,i)),80);if(!f){f=new odb(a);d.c[d.c.length]=f;mdb(f,i,e)}}}}}
function Ofb(a,b){var c,d,e;c=a.c;if(c.a.Y()>1){throw new slb('In straight hyperEdges there may be only one edge.')}QI((e=(new Snb(c.a)).a.bb().mb(),d=Wv((new Ynb(e)).a.H(),21),Wv(d.yb(),12)).a,new HI(b,a.b))}
function no(a,b,c){var d,e;this.f=a;d=Wv(Smb(a.b,b),126);e=!d?0:d.a;bc(c,e);if(c>=(e/2|0)){this.e=!d?null:d.c;this.d=e;while(c++<e){lo(this)}}else{this.c=!d?null:d.b;while(c-->0){ko(this)}}this.b=b;this.a=null}
function HP(a,b){if(typeof klaycallback===Zxb){klaycallback(b)}else{typeof document!==Czb?Rxb(a(b)):"object"===Sxb&&module.exports&&Rxb(a(b));typeof document===Czb&&typeof self!==Czb&&self.postMessage(b)}}
function _P(a,b){var c,d,e,f;if('x' in a.a){e=Wv(Pu(a,'x'),104);b.i.a=e.a}if('y' in a.a){f=Wv(Pu(a,'y'),104);b.i.b=f.a}if(Jzb in a.a){d=Wv(Pu(a,Jzb),104);b.j.a=d.a}if(Kzb in a.a){c=Wv(Pu(a,Kzb),104);b.j.b=c.a}}
function lgb(a,b,c){var d,e;igb(this);b==(fgb(),dgb)?stb(this.g,a.c):stb(this.o,a.c);c==dgb?stb(this.g,a.d):stb(this.o,a.d);stb(this.c,a);d=MX(a.c).b;e=MX(a.d).b;kgb(this,d,e,e);this.f=Zfb(MX(a.c).b,MX(a.d).b)}
function p5(a){var b,c,d,e,f,g;g=new U6(a.d,a.e);for(f=T6(g);f.G();){e=Wv(f.H(),7);d=a.e==(sN(),rN)?e.b:e.e;for(c=new Tob(d);c.a<c.c.c.length;){b=Wv(Rob(c),12);if(!bW(b)&&b.c.f.d!=b.d.f.d){l5(a,b);++a.f;++a.c}}}}
function LQ(a,b,c){var d,e,f,g,h;g=(ypb(),new Frb(Wv(yU(b.a,c),18)));h=new HU(g.b.Y());for(e=new Nqb(g.b.mb());e.b.G();){d=Wv(e.b.H(),37);f=Wv(Smb(a.a,d),31);if(!f){f=e0(d);Umb(a.a,d,f)}h.c[h.c.length]=f}return h}
function T5(a,b){var c,d,e,f;d=new Fnb(a.f.c,0);while(d.b<d.d.Y()){c=(Bxb(d.b<d.d.Y()),Wv(d.d.sb(d.c=d.b++),16));f=b[d.b-1];e=new Fnb(c.a,0);while(e.b<e.d.Y()){Bxb(e.b<e.d.Y());e.d.sb(e.c=e.b++);Enb(e,f[e.b-1])}}}
function m2(a){var b,c;if(MM(Wv(rJ(a,(eM(),TL)),28))){for(c=new Tob(a.f);c.a<c.c.c.length;){b=Wv(Rob(c),7);b.g==(sN(),qN)&&p2(b)}}else{for(c=new Tob(a.f);c.a<c.c.c.length;){b=Wv(Rob(c),7);p2(b)}sJ(a,TL,(KM(),HM))}}
function jpb(a,b,c,d,e,f){var g,h,i,j;g=d-c;if(g<7){gpb(b,c,d,f);return}i=c+e;h=d+e;j=i+(h-i>>1);jpb(b,a,i,j,-e,f);jpb(b,a,j,h,-e,f);if(f.$b(a[j-1],a[j])<=0){while(c<d){Av(b,c++,a[i++])}return}hpb(a,i,j,h,b,c,d,f)}
function hv(a){if(!a){return Bu(),Au}var b=a.valueOf?a.valueOf():a;if(b!==a){var c=dv[typeof b];return c?c(b):kv(typeof b)}else if(a instanceof Array||a instanceof $wnd.Array){return new ku(a)}else{return new Uu(a)}}
function I7(a,b,c){var d,e;d=c.c;e=c.d;if(a.g[d.b]<=a.i[b.b]&&a.i[b.b]<=a.i[d.b]&&a.g[e.b]<=a.i[b.b]&&a.i[b.b]<=a.i[e.b]){if(a.i[d.b]<a.i[e.b]){return false}return true}if(a.i[d.b]<a.i[e.b]){return true}return false}
function j5(a,b,c){var d,e,f,g,h,i,j,k;j=0;for(e=a.a[b],f=0,g=e.length;f<g;++f){d=e[f];k=new U6(d,c);for(i=T6(k);i.G();){h=Wv(i.H(),7);Umb(a.f,h,Elb(j));LM(Wv(rJ(d,(eM(),TL)),28))&&++j}LM(Wv(rJ(d,(eM(),TL)),28))||++j}}
function Pb(a,b,c){var d,e;_b(b);if(c.G()){e=Wv(c.H(),21);vmb(b,Mb(a.a,e.yb()));vmb(b,a.b);vmb(b,Mb(a.a,e.zb()));while(c.G()){vmb(b,a.a.c);d=Wv(c.H(),21);vmb(b,Mb(a.a,d.yb()));vmb(b,a.b);vmb(b,Mb(a.a,d.zb()))}}return b}
function Gd(a,b){var c,d;c=Wv(Wmb(a.b,b),19);if(!c){return a.$()}d=a.Z();d.jb(c);a.c-=c.Y();c.Q();return aw(d,137)?(ypb(),new dsb(Wv(d,137))):aw(d,18)?(ypb(),new Frb(Wv(d,18))):aw(d,20)?Hpb(Wv(d,20)):(ypb(),new zqb(d))}
function Tm(a,b){var c;b.d?(b.d.b=b.b):(a.a=b.b);b.b?(b.b.d=b.d):(a.e=b.d);if(!b.e&&!b.c){c=Wv(Wmb(a.b,b.a),126);c.a=0;++a.c}else{c=Wv(Smb(a.b,b.a),126);--c.a;!b.e?(c.b=b.c):(b.e.c=b.c);!b.c?(c.c=b.e):(b.c.e=b.e)}--a.d}
function mU(a,b,c){switch(c.e){case 1:return new HI(b.a,Qlb(a.d.b,b.b));case 2:return new HI(Nlb(a.c.a,b.a),b.b);case 3:return new HI(b.a,Nlb(a.c.b,b.b));case 4:return new HI(Qlb(b.a,a.d.a),b.b);}return new HI(b.a,b.b)}
function Oxb(a){var b,c,d,e;b=0;d=(bmb(),a.length);e=d-4;c=0;while(c<e){b=a.charCodeAt(c+3)+31*(a.charCodeAt(c+2)+31*(a.charCodeAt(c+1)+31*(a.charCodeAt(c)+31*b)));b=b|0;c+=4}while(c<d){b=b*31+jmb(a,c++)}b=b|0;return b}
function X9(a,b){var c,d,e;this.a=a;this.c=b;this.b=xv(nE,Txb,673,a.length,0,2);for(c=0;c<a.length;++c){e=a[c].length;this.b[c]=xv(nE,{673:1,3:1,5:1,6:1},102,e,0,1);for(d=0;d<e;++d){this.b[c][d]=new $9(this,a[c][d].c)}}}
function sk(a,b,c,d,e,f,g){var h;this.a=Wv(_b(a),56);this.b=b;this.c=e;this.e=c;this.d=Wv(_b(d),159);this.g=f;this.f=Wv(_b(g),159);b&&a.$b(c,c);e&&a.$b(f,f);if(b&&e){h=a.$b(c,f);Zb(h<=0,c,f);h==0&&Xb(d!=(Gh(),Fh)|g!=Fh)}}
function eV(a){this.a=a;if(a.c.f.g==(CX(),xX)){this.c=a.c;this.d=Wv(rJ(a.c.f,(Rib(),hib)),32)}else if(a.d.f.g==xX){this.c=a.d;this.d=Wv(rJ(a.d.f,(Rib(),hib)),32)}else{throw new slb('Edge '+a+' is not an external edge.')}}
function Xcb(){Xcb=iI;Scb=UQ(new WQ,(d0(),x_));Ucb=TQ(new WQ,A_);Vcb=PQ(TQ(new WQ,R_),Q_);Rcb=PQ(UQ(TQ(new WQ,s_),t_),u_);Wcb=TQ(new WQ,Z_);Tcb=PQ(new WQ,y_);Pcb=PQ(UQ(TQ(SQ(new WQ,D_),F_),H_),E_);Qcb=PQ(UQ(new WQ,H_),q_)}
function Lr(a,b,c){var d,e,f,g;Mh(c,Xyb);if(c==0){return Pr(a,b)}Xb(ok(a.b,b));g=a.c.a;if(!g){a.d.$b(b,b);e=new Os(b,c);es(a.a,e,a.a);Us(a.c,null,e);return 0}f=xv(mw,Yyb,26,1,12,1);d=zs(g,a.d,b,c,f);Us(a.c,g,d);return f[0]}
function i$(a,b,c){var d,e,f,g,h,i;d=0;i=c;if(!b){d=c*(a.c.length-1);i*=-1}for(f=new Tob(a);f.a<f.c.c.length;){e=Wv(Rob(f),9);sJ(e,(eM(),lL),(iK(),eK));e.j.a=d;for(h=nX(e,(sN(),ZM)).mb();h.G();){g=Wv(h.H(),7);g.i.a=d}d+=i}}
function Fd(a,b,c){var d;d=Wv(Smb(a.b,b),19);if(!d){d=a.Z();if(d.ib(c)){++a.c;Umb(a.b,b,d);return true}else{throw new ukb('New Collection violated the Collection spec')}}else if(d.ib(c)){++a.c;return true}else{return false}}
function ES(a,b,c){var d,e,f;CS(a,b,c);f=new GU;for(e=new Tob(a.b.a.b);e.a<e.c.c.length;){d=Wv(Rob(e),25);if(b.D(d)){vU(f,new OS(d,true));vU(f,new OS(d,false))}}JS(a.d);RT(f,a.c,new opb(Bv(tv(JA,1),syb,160,0,[a.d])));DS(a,b,c)}
function R8(a,b){var c,d,e,f,g;a.c[b.k]=true;vU(a.a,b);for(g=new Tob(b.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);for(d=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[f.b,f.e]))))));Cm(d);){c=Wv(Dm(d),12);e=S8(f,c).f;a.c[e.k]||R8(a,e)}}}
function dQ(a,b,c,d){var e,f,g;if('labels' in b.a){g=Pu(b,'labels');if(!g.hc()){throw new GQ("The 'labels' property of a node must be an array.",g,b)}f=g.hc();for(e=0;e<f.a.length;++e){aw(gu(f,e),69)&&cQ(a,Wv(gu(f,e),69),c,d)}}}
function j0(a,b,c){var d,e,f,g,h,i;f=Wv(yU(b.b,0),12).c;d=f.f;e=d.g;i=Wv(yU(c.e,0),12).d;g=i.f;h=g.g;e==(CX(),zX)?sJ(a,(Rib(),qib),Wv(rJ(d,qib),7)):sJ(a,(Rib(),qib),f);h==zX?sJ(a,(Rib(),rib),Wv(rJ(g,rib),7)):sJ(a,(Rib(),rib),i)}
function oM(){oM=iI;gM=new pM('H_LEFT',0);fM=new pM('H_CENTER',1);iM=new pM('H_RIGHT',2);nM=new pM('V_TOP',3);mM=new pM('V_CENTER',4);lM=new pM('V_BOTTOM',5);jM=new pM('INSIDE',6);kM=new pM('OUTSIDE',7);hM=new pM('H_PRIORITY',8)}
function rS(a){aS();var b,c,d;this.b=ZR;this.c=_R;this.d=(sK(),qK);this.g=(VR(),UR);this.a=a;oS(this,new sS);fS(this);for(d=new Tob(a.b);d.a<d.c.c.length;){c=Wv(Rob(d),25);if(!c.f){b=new QR(Bv(tv(kA,1),syb,25,0,[c]));vU(a.a,b)}}}
function R7(a,b){var c,d,e,f;e=1;b.j=true;for(d=new Tob(m7(b));d.a<d.c.c.length;){c=Wv(Rob(d),89);if(!a.c[c.b]){a.c[c.b]=true;f=c7(c,b);if(c.e){e+=R7(a,f)}else if(!f.j&&c.a==c.d.e-c.c.e){c.e=true;stb(a.p,c);e+=R7(a,f)}}}return e}
function Abb(a){var b,c,d,e,f,g,h,i;e=Uzb;d=Vzb;for(c=new Tob(a.e.c);c.a<c.c.c.length;){b=Wv(Rob(c),16);for(g=new Tob(b.a);g.a<g.c.c.length;){f=Wv(Rob(g),9);i=Ixb(a.n[f.k]);h=i+Ixb(a.b[a.f[f.k].k]);e=e<i?e:i;d=d>h?d:h}}return d-e}
function DQ(a){var b;b=new Tu;Ru(b,'type',new lv((Gkb($z),$z.n)));Ru(b,Dzb,new lv(a.f));!!a.b&&Ru(b,'value',a.b);!!a.a&&Ru(b,'context',a.a);Ru(b,Ezb,new lv(Hb(new Kb('\n'),new wnb(new opb((a.g==null&&(a.g=Pt(a)),a.g))))));return b}
function D5(a,b){if(a.c<b.c){return -1}else if(a.c>b.c){return 1}else if(a.b<b.b){return -1}else if(a.b>b.b){return 1}else if(a.a!=b.a){return a.a.b-b.a.b}else if(a.d==0&&b.d==1){return -1}else if(a.d==1&&b.d==0){return 1}return 0}
function cn(a,b){var c,d,e,f,g;if(b===a){return true}if(!aw(b,20)){return false}g=Wv(b,20);if(a.Y()!=g.Y()){return false}f=g.mb();for(d=a.mb();d.G();){c=d.H();e=f.H();if(!(gw(c)===gw(e)||c!=null&&rb(c,e))){return false}}return true}
function st(b){var c=(!qt&&(qt=tt()),qt);var d=b.replace(/[\x00-\x1f\xad\u0600-\u0603\u06dd\u070f\u17b4\u17b5\u200b-\u200f\u2028-\u202e\u2060-\u2064\u206a-\u206f\ufeff\ufff9-\ufffb"\\]/g,function(a){return rt(a,c)});return '"'+d+'"'}
function ER(a,b){var c,d,e,f,g,h,i;e=b==1?wR:vR;for(d=(g=(new Snb(e.a)).a.bb().mb(),new Ynb(g));d.a.G();){c=(f=Wv(d.a.H(),21),Wv(f.yb(),59));for(i=Wv(Dd(a.f.c,c),18).mb();i.G();){h=Wv(i.H(),27);BU(a.b.b,h.b);BU(a.b.a,Wv(h.b,25).f)}}}
function aR(a,b,c){var d,e,f,g;nI(c,'Recursive layout',2);if(b.b.c.length!=0){g=1/b.b.c.length;for(f=new Tob(b.b);f.a<f.c.c.length;){e=Wv(Rob(f),9);d=Wv(rJ(e,(Rib(),sib)),55);if(d){aR(a,d,rI(c,g));$Q(e,d)}}NQ(a.d,b);_Q(b,c)}bR(b);pI(c)}
function L3(a,b){oR.call(this);this.d=new vtb;this.b=Wv(rJ(b,(Rib(),Jib)),15).a*Wv(rJ(b,(Mjb(),qjb)),15).a;this.e=this.b*Wv(rJ(b,Ejb),15).a;this.a=new jJ;this.c=new jJ;this.j=new VN(a.j,a.k,0,a.n-a.k);this.o=a.g;this.g.a=a.i;K3(this,a)}
function Mtb(a,b){var c,d,e,f,g;f=b==null?0:a.b.Vc(b);d=(c=Ttb(a.a,f),c==null?[]:c);for(g=0;g<d.length;g++){e=d[g];if(a.b.Uc(b,e.yb())){if(d.length==1){d.length=0;a.a[$Ab](f)}else{d.splice(g,1)}--a.c;msb(a.b);return e.zb()}}return null}
function hU(a,b,c){var d;d=null;!!b&&(d=b.e);ZU(a,new VS(b.i.a-d.b+c.a,b.i.b-d.d+c.b));ZU(a,new VS(b.i.a-d.b+c.a,b.i.b+b.j.b+d.a+c.b));ZU(a,new VS(b.i.a+b.j.a+d.c+c.a,b.i.b-d.d+c.b));ZU(a,new VS(b.i.a+b.j.a+d.c+c.a,b.i.b+b.j.b+d.a+c.b))}
function J2(a,b){switch(b.e){case 2:QX(a,(sN(),ZM));a.a.a=a.j.a;a.a.b=a.j.b/2;break;case 4:QX(a,(sN(),rN));a.a.a=0;a.a.b=a.j.b/2;break;case 1:QX(a,(sN(),$M));a.a.a=a.j.a/2;a.a.b=0;break;case 3:QX(a,(sN(),pN));a.a.a=a.j.a/2;a.a.b=a.j.b;}}
function Fq(a,b){Dq();var c,d,e;if(b===a){return true}if(aw(b,207)){e=Wv(b,207);if(a.Y()!=e.Y()||Vg(a).Y()!=e.bb().Y()){return false}for(d=e.bb().mb();d.G();){c=Wv(d.H(),83);if(a.Cb(c.Zb())!=c.Yb()){return false}}return true}return false}
function wvb(a,b){var c,d,e,f,g,h;f=a.a*_Ab+a.b*1502;h=a.b*_Ab+11;c=Math.floor(h*FAb);f+=c;h-=c*aBb;f%=aBb;a.a=f;a.b=h;if(b<=24){return Mlb(a.a*qvb[b])}else{e=a.a*(1<<b-24);g=Mlb(a.b*rvb[b]);d=e+g;d>=2147483648&&(d-=4294967296);return d}}
function MW(a,b,c){var d,e,f;if(b==c){return}d=b;do{vI(a,d.d);f=Wv(rJ(d,(Rib(),zib)),9);if(f){e=d.a;uI(a,e.b,e.d);vI(a,f.i);d=hX(f)}}while(f);d=c;do{EI(a,d.d);f=Wv(rJ(d,(Rib(),zib)),9);if(f){e=d.a;DI(a,e.b,e.d);EI(a,f.i);d=hX(f)}}while(f)}
function n3(a,b){var c,d,e,f,g,h;c=new GU;h=new Um;for(e=(g=(new Snb(a.a)).a.bb().mb(),new Ynb(g));e.a.G();){d=(f=Wv(e.a.H(),21),Wv(f.yb(),12));Nm(h,d.c,d,null);Nm(h,d.d,d,null)}while(h.a){vU(c,m3(h,b,LM(Wv(rJ(b,(eM(),TL)),28))))}return c}
function B7(a,b){var c,d,e,f,g;for(f=new Tob(a.e.a);f.a<f.c.c.length;){e=Wv(Rob(f),61);if(e.c.c.length==e.g.c.length){d=e.e;g=M7(e);for(c=e.e-Wv(g.a,24).a+1;c<e.e+Wv(g.b,24).a;c++){b[c]<b[d]&&(d=c)}if(b[d]<b[e.e]){--b[e.e];++b[d];e.e=d}}}}
function zR(a,b){var c,d,e,f,g,h,i;e=b==1?wR:vR;for(d=(g=(new Snb(e.a)).a.bb().mb(),new Ynb(g));d.a.G();){c=(f=Wv(d.a.H(),21),Wv(f.yb(),59));for(i=Wv(Dd(a.f.c,c),18).mb();i.G();){h=Wv(i.H(),27);vU(a.b.b,Wv(h.b,25));vU(a.b.a,Wv(h.b,25).f)}}}
function ecb(a){$bb();var b,c,d,e,f,g,h;c=(mp(),new wub);for(e=new Tob(a.e.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);for(g=new Tob(d.a);g.a<g.c.c.length;){f=Wv(Rob(g),9);h=a.f[f.k];b=Wv(rub(c,h),20);if(!b){b=new GU;tub(c,h,b)}b.ib(f)}}return c}
function cS(a,b){var c,d,e,f;for(d=new Tob(a.a.a);d.a<d.c.c.length;){c=Wv(Rob(d),78);c.i=true}for(f=new Tob(a.a.b);f.a<f.c.c.length;){e=Wv(Rob(f),25);e.p=Ckb(Ixb(Xv(a.f.B(new RJ(e,b)))));e.f.i=e.f.i&Ckb(Ixb(Xv(a.f.B(new RJ(e,b)))))}return a}
function RY(a,b){var c,d,e,f;e=Eo(mX(b));for(d=WI(e,0);d.b!=d.d.c;){c=Wv(_ub(d),12);f=c.d.f;if(f.g==(CX(),wX)&&!(Ckb(Ixb(Xv(rJ(f,(Rib(),Vhb)))))&&rJ(f,uib)!=null)){BU(f.d.a,f);PX(c.c,null);PX(c.d,null);return RY(a,f)}else{return b}}return b}
function D7(a,b){var c,d,e,f,g,h,i;if(!b.e){throw new slb('The input edge is not a tree edge.')}f=null;e=$xb;for(d=new Tob(a.d);d.a<d.c.c.length;){c=Wv(Rob(d),89);h=c.c;i=c.d;if(I7(a,h,b)&&!I7(a,i,b)){g=i.e-h.e-c.a;if(g<e){e=g;f=c}}}return f}
function Icb(a,b){var c,d,e,f,g;f=b.a;f.c.f==b.b?(g=f.d):(g=f.c);f.c.f==b.b?(d=f.c):(d=f.d);e=vbb(a.a,g,d);if(e>0&&e<rAb){c=wbb(a.a,d.f,e);Bbb(a.a,d.f,-c);return c>0}else if(e<0&&-e<rAb){c=xbb(a.a,d.f,-e);Bbb(a.a,d.f,c);return c>0}return false}
function Odb(a,b,c,d,e){var f,g;if(!yI(MI(Bv(tv(qz,1),Fzb,10,0,[e.f.i,e.i,e.a])),c)){b.c==e?rn(b.a,0,new II(c)):QI(b.a,new II(c));if(d&&!ttb(a.a,c)){g=Wv(rJ(b,(eM(),CL)),44);if(!g){g=new jJ;sJ(b,CL,g)}f=new II(c);TI(g,f,g.c.b,g.c);stb(a.a,f)}}}
function Pdb(a){var b,c,d,e,f,g,h;b=0;for(d=new Tob(a.a);d.a<d.c.c.length;){c=Wv(Rob(d),9);for(f=Uh(mX(c));Cm(f);){e=Wv(Dm(f),12);if(a==e.d.f.d&&e.c.g==(sN(),rN)){g=MX(e.c).b;h=MX(e.d).b;b=b>(h-g<=0?0-(h-g):h-g)?b:h-g<=0?0-(h-g):h-g}}}return b}
function yo(a,b){var c,d,e;if(gw(b)===gw(_b(a))){return true}if(!aw(b,20)){return false}d=Wv(b,20);e=a.Y();if(e!=d.Y()){return false}if(aw(d,63)){for(c=0;c<e;c++){if(!Tb(a.sb(c),d.sb(c))){return false}}return true}else{return Ol(a.mb(),d.mb())}}
function I8(a,b){var c,d,e,f,g,h,i,j;e=a.b[b.k];if(e>=0){return e}else{f=1;for(h=new Tob(b.f);h.a<h.c.c.length;){g=Wv(Rob(h),7);for(d=new Tob(g.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);j=c.d.f;if(b!=j){i=I8(a,j);f=f>i+1?f:i+1}}}H8(a,b,f);return f}}
function edb(a,b,c){var d,e,f,g,h,i;d=0;if(a.b!=0&&b.b!=0){f=WI(a,0);g=WI(b,0);h=Ixb(Yv(_ub(f)));i=Ixb(Yv(_ub(g)));e=true;do{h>i-c&&h<i+c&&++d;h<=i&&f.b!=f.d.c?(h=Ixb(Yv(_ub(f)))):i<=h&&g.b!=g.d.c?(i=Ixb(Yv(_ub(g)))):(e=false)}while(e)}return d}
function sv(a,b){switch(uv(a)){case 5:return ew(b);case 6:return cw(b);case 7:return bw(b);case 0:return Vv(b,a.__elementTypeId$);case 2:return fw(b)&&!(b.ad===kI);case 1:return fw(b)&&!(b.ad===kI)||Vv(b,a.__elementTypeId$);default:return true;}}
function Lv(a,b){var c,d,e,f,g;b&=63;c=a.h;d=(c&524288)!=0;d&&(c|=-1048576);if(b<22){g=c>>b;f=a.m>>b|c<<22-b;e=a.l>>b|a.m<<22-b}else if(b<44){g=d?bzb:0;f=c>>b-22;e=a.m>>b-22|c<<44-b}else{g=d?bzb:0;f=d?azb:0;e=c>>b-44}return Ev(e&azb,f&azb,g&bzb)}
function O9(a,b){switch(a.e){case 1:switch(b.e){case 1:return 1;case 4:return 2;case 3:return 3;case 2:return 4;}break;case 2:switch(b.e){case 1:return 1;case 2:return 2;case 3:return 3;case 4:return 4;}break;default:throw new slb(GAb);}return 0}
function hZ(a,b,c){var d,e,f,g,h,i;d=new GU;d.c[d.c.length]=b;i=b;h=0;do{i=mZ(a,i);!!i&&(d.c[d.c.length]=i,true);++h}while(i);g=(c-(d.c.length-1)*a.d.d)/d.c.length;for(f=new Tob(d);f.a<f.c.c.length;){e=Wv(Rob(f),9);e.j.a=g}return new RJ(Elb(h),g)}
function kZ(a,b,c){var d,e,f,g,h,i;d=new GU;d.c[d.c.length]=b;i=b;h=0;do{i=lZ(a,i);!!i&&(d.c[d.c.length]=i,true);++h}while(i);g=(c-(d.c.length-1)*a.d.d)/d.c.length;for(f=new Tob(d);f.a<f.c.c.length;){e=Wv(Rob(f),9);e.j.a=g}return new RJ(Elb(h),g)}
function m$(a){var b,c,d,e,f,g;e=Wv(yU(a.f,0),7);g=0;for(d=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[new fY(e),new lY(e)]))))));Cm(d);){c=Wv(Dm(d),7);g+=c.f.i.a+c.i.a+c.a.a}b=Wv(rJ(a,(eM(),SL)),10);f=!b?0:b.a;a.i.a=g/(e.b.c.length+e.e.c.length)-f}
function Ueb(a,b){var c,d,e,f;if(b<2*a.c){throw new slb('The knot vector must have at least two time the dimension elements.')}a.j=0;a.i=1;for(d=0;d<a.c;d++){a.g.ib(0)}f=b+1-2*a.c;for(e=1;e<f;e++){a.g.ib(e/f)}if(a.e){for(c=0;c<a.c;c++){a.g.ib(1)}}}
function Fs(a){var b,c;c=a.c;a.c=0;ds(a.f,a.i);if(!a.e){return a.g}else if(!a.g){return a.e}else if(a.e.d>=a.g.d){b=a.f;b.e=Is(a.e,b);b.g=a.g;b.a=a.a-1;b.j=XH(a.j,c);return Gs(b)}else{b=a.i;b.g=Js(a.g,b);b.e=a.e;b.a=a.a-1;b.j=XH(a.j,c);return Gs(b)}}
function e2(a){var b,c,d,e,f,g;for(e=new Tob(a.a);e.a<e.c.c.length;){d=Wv(Rob(e),9);if(d.g==(CX(),BX)){f=Wv(rJ(d,(Rib(),nib)),9);c=d.f;b=(Cxb(0,c.c.length),Wv(c.c[0],7));g=Wv(rJ(b,uib),7);g.g==(sN(),$M)&&d.k>f.k?QX(g,pN):g.g==pN&&f.k>d.k&&QX(g,$M)}}}
function q3(a,b,c){var d,e,f,g,h,i,j;j=a.b;g=0;for(f=new Tob(a.a.b);f.a<f.c.c.length;){e=Wv(Rob(f),33);g=Nlb(g,e.j.a)}i=wfb(a.a.c,a.a.d,b,c,g);Ue(a.a.a,Veb(i));h=s3(a.a.b,i.a,j);d=new Dfb((!i.k&&(i.k=new Efb(Xeb(i))),i.k));zfb(d);return !h?d:Gfb(d,h)}
function wbb(a,b,c){var d,e,f,g,h,i,j;d=c;e=b;do{e=a.a[e.k];g=(j=a.f[e.k],Ixb(a.n[j.k])+Ixb(a.d[e.k])-e.e.d);h=zbb(e,!e.d?-1:zU(e.d.a,e,0));if(h){f=(i=a.f[h.k],Ixb(a.n[i.k])+Ixb(a.d[h.k])+h.j.b+h.e.a);d=Qlb(d,g-(f+Xjb(a.j,e,h)))}}while(b!=e);return d}
function xbb(a,b,c){var d,e,f,g,h,i,j;d=c;e=b;do{e=a.a[e.k];f=(j=a.f[e.k],Ixb(a.n[j.k])+Ixb(a.d[e.k])+e.j.b+e.e.a);h=ybb(e,!e.d?-1:zU(e.d.a,e,0));if(h){g=(i=a.f[h.k],Ixb(a.n[i.k])+Ixb(a.d[h.k])-h.e.d);d=Qlb(d,g-(f+Xjb(a.j,e,h)))}}while(b!=e);return d}
function Sr(b,c,d){var e,f,g;Mh(d,Xyb);if(d==0){return Pr(b,c)}g=b.c.a;f=xv(mw,Yyb,26,1,12,1);try{if(!ok(b.b,c)||!g){return 0}e=Hs(g,b.d,c,d,f)}catch(a){a=OH(a);if(aw(a,119)){return 0}else if(aw(a,76)){return 0}else throw NH(a)}Us(b.c,g,e);return f[0]}
function MO(a,b){var c,d,e,f,g;if(a.b){d=Wv(oW(a.e,(eM(),jL)),65);e=d.b+d.c;c=d.d+d.a}else{e=b*2;c=b*2}g=Nlb(a.o[1]>0?e+a.i[1]*b+a.n[1]:0,a.o[3]>0?e+a.i[3]*b+a.n[3]:0);f=Nlb(a.o[4]>0?c+a.i[4]*b+a.n[4]:0,a.o[2]>0?c+a.i[2]*b+a.n[2]:0);return new HI(g,f)}
function b$(a){var b,c,d,e,f,g;g=Wv(FU(a.a,xv(qB,Nzb,9,a.a.c.length,0,1)),51);lpb(g,new g$);c=null;for(e=0,f=g.length;e<f;++e){d=g[e];if(d.g!=(CX(),xX)){break}b=Wv(rJ(d,(Rib(),hib)),32);if(b!=(sN(),rN)&&b!=ZM){continue}!!c&&Wv(rJ(c,oib),20).ib(d);c=d}}
function j6(a,b,c,d,e){var f,g,h,i;i=new U6(b,d);for(h=T6(i);h.G();){f=Wv(h.H(),7);Umb(a.k,f,Elb(Wv(Smb(a.k,f),24).a+Wv(re(Ktb(e.d,c)),24).a))}i=new U6(c,d);for(g=T6(i);g.G();){f=Wv(g.H(),7);Umb(a.k,f,Elb(Wv(Smb(a.k,f),24).a-Wv(re(Ktb(e.d,b)),24).a))}}
function hI(a,b,c){var d=fI,h;var e=d[a];var f=e instanceof Array?e[0]:null;if(e&&!f){_=e}else{_=(h=b&&b.prototype,!h&&(h=fI[b]),jI(h));_._c=c;_.constructor=_;!b&&(_.ad=kI);d[a]=_}for(var g=3;g<arguments.length;++g){arguments[g].prototype=_}f&&(_.$c=f)}
function Wkb(a){if(a.Sc()){var b=a.c;b.Tc()?(a.n='['+b.k):!b.Sc()?(a.n='[L'+b.Qc()+';'):(a.n='['+b.Qc());a.b=b.Pc()+'[]';a.j=b.Rc()+'[]';return}var c=a.i;var d=a.d;d=d.split('/');a.n=Zkb('.',[c,Zkb('$',d)]);a.b=Zkb('.',[c,Zkb('.',d)]);a.j=d[d.length-1]}
function Mr(a,b,c){var d;if(!c){return 0}d=a.d.$b(a.b.g,c.b);if(d>0){return Mr(a,b,c.g)}else if(d==0){switch(a.b.f.e){case 0:return PH(b._b(c),b.ac(c.g));case 1:return b.ac(c.g);default:throw new tkb;}}else{return PH(PH(b.ac(c.g),b._b(c)),Mr(a,b,c.e))}}
function Nr(a,b,c){var d;if(!c){return 0}d=a.d.$b(a.b.e,c.b);if(d<0){return Nr(a,b,c.e)}else if(d==0){switch(a.b.d.e){case 0:return PH(b._b(c),b.ac(c.e));case 1:return b.ac(c.e);default:throw new tkb;}}else{return PH(PH(b.ac(c.e),b._b(c)),Nr(a,b,c.g))}}
function z2(a,b,c,d){var e,f,g,h;g=new uX(a);sX(g,(CX(),zX));sJ(g,(Rib(),uib),b);sJ(g,(eM(),TL),(KM(),FM));sJ(g,qib,c);sJ(g,rib,d);f=new RX;QX(f,(sN(),rN));PX(f,g);h=new RX;QX(h,ZM);PX(h,g);eW(b,f);e=new hW;qJ(e,b);sJ(e,CL,null);dW(e,h);eW(e,d);return g}
function e6(a,b){var c,d,e,f,g,h,i,j,k,l;c=0;for(g=a.j,h=0,i=g.length;h<i;++h){f=g[h];l=new U6(f,b);for(k=T6(l);k.G();){j=Wv(k.H(),7);for(e=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[j.b,j.e]))))));Cm(e);){d=Wv(Dm(e),12);bW(d)||(c+=b6(a,d,j))}}}return c}
function qab(a,b){if(a.c<b.c){return -1}else if(a.c>b.c){return 1}else if(a.b<b.b){return -1}else if(a.b>b.b){return 1}else if(a.a!=b.a){return txb(a.a)-txb(b.a)}else if(a.d==(vab(),uab)&&b.d==tab){return -1}else if(a.d==tab&&b.d==uab){return 1}return 0}
function R4(a){var b,c,d,e,f,g;e=new aJ;for(d=new Tob(a.d.a);d.a<d.c.c.length;){c=Wv(Rob(d),61);c.c.c.length==0&&(TI(e,c,e.c.b,e.c),true)}if(e.b>1){b=x7(y7(new A7,a.b++),a.d);for(g=WI(e,0);g.b!=g.d.c;){f=Wv(_ub(g),61);f7(i7(h7(j7(g7(new k7,1),0),b),f))}}}
function p3(a,b,c,d){var e,f,g,h,i,j;j=0;for(g=new Tob(a.a.b);g.a<g.c.c.length;){f=Wv(Rob(g),33);j=Nlb(j,f.j.a)}i=vfb(a.a.c,b,a.a.d,d,Jeb(a.b),c);Ue(a.a.a,Veb(i));h=s3(a.a.b,i.a,a.b);e=new Dfb((!i.k&&(i.k=new Efb(Xeb(i))),i.k));zfb(e);return !h?e:Gfb(e,h)}
function M0(a,b){var c,d,e,f,g;for(d=new Tob(a.b);d.a<d.c.c.length;){c=Wv(Rob(d),33);sJ(c,(Rib(),pib),b)}for(g=new Tob(a.c.c);g.a<g.c.c.length;){e=Wv(Rob(g),33);sJ(e,(Rib(),pib),b)}for(f=new Tob(a.d.c);f.a<f.c.c.length;){e=Wv(Rob(f),33);sJ(e,(Rib(),pib),b)}}
function I1(){I1=iI;G1=new J1(tzb,0);B1=new J1('NIKOLOV',1);E1=new J1('NIKOLOV_PIXEL',2);C1=new J1('NIKOLOV_IMPROVED',3);D1=new J1('NIKOLOV_IMPROVED_PIXEL',4);A1=new J1('DUMMYNODE_PERCENTAGE',5);F1=new J1('NODECOUNT_PERCENTAGE',6);H1=new J1('NO_BOUNDARY',7)}
function cab(a,b){var c,d,e,f,g;f=0;g=Wv(re(Ktb(b.d,a)),24);if(!g){return 0}for(e=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[a.b,a.e]))))));Cm(e);){d=Wv(Dm(e),12);d.c==a?(c=Wv(Smb(b,d.d),24)):(c=Wv(Smb(b,d.c),24));!!c&&g.a>c.a&&(f=Plb(f,g.a-c.a-1))}return f}
function RZ(a){var b,c;b=Wv(rJ(a,(eM(),HL)),15).a;c=Wv(rJ(a,IL),15).a;sJ(a,IL,new llb(b));sJ(a,HL,new llb(c));switch(Wv(rJ(a,lL),103).e){case 1:sJ(a,lL,(iK(),hK));break;case 2:sJ(a,lL,(iK(),dK));break;case 3:sJ(a,lL,(iK(),fK));break;case 4:sJ(a,lL,(iK(),gK));}}
function N0(a){var b,c,d,e,f;for(e=(Il(),new Im(Dl(ul(a.a,new yl))));Cm(e);){d=Wv(Dm(e),9);if(d.g==(CX(),yX)){f=P0(d)?(kP(),hP):(kP(),gP);sJ(d,(Rib(),pib),f)}for(c=Uh(mX(d));Cm(c);){b=Wv(Dm(c),12);f=Ckb(Ixb(Xv(rJ(b,(Rib(),Iib)))))?(kP(),gP):(kP(),hP);M0(b,f)}}}
function O0(a){var b,c,d,e,f;for(e=(Il(),new Im(Dl(ul(a.a,new yl))));Cm(e);){d=Wv(Dm(e),9);if(d.g==(CX(),yX)){f=P0(d)?(kP(),gP):(kP(),hP);sJ(d,(Rib(),pib),f)}for(c=Uh(mX(d));Cm(c);){b=Wv(Dm(c),12);f=Ckb(Ixb(Xv(rJ(b,(Rib(),Iib)))))?(kP(),hP):(kP(),gP);M0(b,f)}}}
function jdb(a,b,c){var d,e,f;for(f=new Tob(a.e);f.a<f.c.c.length;){d=Wv(Rob(f),118);if(d.b.d<0&&d.c>0){d.b.c-=d.c;d.b.c<=0&&d.b.f>0&&QI(b,d.b)}}for(e=new Tob(a.b);e.a<e.c.c.length;){d=Wv(Rob(e),118);if(d.a.d<0&&d.c>0){d.a.f-=d.c;d.a.f<=0&&d.a.c>0&&QI(c,d.a)}}}
function agb(a,b,c){var d,e,f;for(f=new Tob(a.j);f.a<f.c.c.length;){d=Wv(Rob(f),117);if(d.b.i<0&&d.c>0){d.b.e-=d.c;d.b.e<=0&&d.b.k>0&&QI(b,d.b)}}for(e=new Tob(a.d);e.a<e.c.c.length;){d=Wv(Rob(e),117);if(d.a.i<0&&d.c>0){d.a.k-=d.c;d.a.k<=0&&d.a.e>0&&QI(c,d.a)}}}
function tj(a){var b,c,d,e,f;f=a.d.c+a.e.c;switch(f){case 0:return dr(),cr;case 1:d=Wv(Sl(new rnb((new inb(a)).a)),21);return Bj(d.yb(),d.zb());default:e=(mp(),new wub);for(c=new rnb((new inb(a)).a);c.b;){b=pnb(c);tub(e,_b(b.yb()),_b(b.zb()))}return new ir(e);}}
function DS(a,b,c){var d,e,f;for(e=new Tob(a.b.a.b);e.a<e.c.c.length;){d=Wv(Rob(e),25);if(!b.D(d)){continue}f=Ixb(Yv(c.B(d)));if(f>0){!(tK(a.b.d)&&d.q.d)&&!(uK(a.b.d)&&d.q.b)&&(d.j.e+=0>f/2-0.5?0:f/2-0.5);!(tK(a.b.d)&&d.q.a)&&!(uK(a.b.d)&&d.q.c)&&(d.j.b-=f-1)}}}
function R9(a,b){switch(a.e){case 1:switch(b.e){case 1:return HAb;case 4:return 0.5;case 3:return IAb;case 2:return JAb;}break;case 2:switch(b.e){case 1:return HAb;case 2:return 0.5;case 3:return IAb;case 4:return JAb;}break;default:throw new slb(GAb);}return 0}
function rT(a,b){var c,d,e,f;f=new Fnb(a,0);c=(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),48));while(f.b<f.d.Y()){d=(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),48));e=new WS(d.c,c.d,b);Bxb(f.b>0);f.a.sb(f.c=--f.b);Anb(f,e);Bxb(f.b<f.d.Y());f.d.sb(f.c=f.b++);e.a=false;c=d}}
function oZ(a){var b,c,d,e,f,g;e=Wv(rJ(a,(Rib(),Zhb)),7);for(g=new Tob(a.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);for(d=new Tob(f.e);d.a<d.c.c.length;){b=Wv(Rob(d),12);eW(b,e);return f}for(c=new Tob(f.b);c.a<c.c.c.length;){b=Wv(Rob(c),12);dW(b,e);return f}}return null}
function i6(a,b,c,d,e){var f,g,h,i,j,k;g=b;f=0;h=false;k=new U6(c,d);for(j=T6(k);j.G();){i=Wv(j.H(),7);h=true;Umb(a.k,i,Elb(g));if(LM(Wv(rJ(c,(eM(),TL)),28))||i.b.c.length+i.e.c.length>1){++f;++g}}if(!LM(Wv(rJ(c,(eM(),TL)),28))&&h){++f;++g}Umb(e,c,Elb(f));return g}
function nfb(a){var b,c,d,e,f,g,h,i,j,k,l,m;g=a.b.mb();h=Wv(g.H(),92);k=h.a.a;j=k>RAb;i=k<SAb;while(g.G()){c=h;f=k;e=j;d=i;h=Wv(g.H(),92);k=h.a.a;j=k>RAb;i=k<SAb;if(!(j||i)){return mfb(h.b)}if(e&&i||d&&j){b=f/(f-k);l=mfb(c.b);m=mfb(h.b);return b*l+(1-b)*m}}return 0}
function ofb(a){var b,c,d,e,f,g,h,i,j,k,l,m;g=a.b.mb();h=Wv(g.H(),92);k=h.a.b;j=k>RAb;i=k<SAb;while(g.G()){c=h;f=k;e=j;d=i;h=Wv(g.H(),92);k=h.a.b;j=k>RAb;i=k<SAb;if(!(j||i)){return mfb(h.b)}if(e&&i||d&&j){b=f/(f-k);l=mfb(c.b);m=mfb(h.b);return b*l+(1-b)*m}}return 0}
function b6(a,b,c){var d,e;d=0;if(d6(b)){if(ttb(a.g,b)){Sr(a.i,Elb(h6(a,b.c)),1)>0;Sr(a.i,Elb(h6(a,b.d)),1)>0;utb(a.g,b);d+=g6(a,b,a.i)}else{stb(a.g,b);Lr(a.i,Elb(h6(a,b.c)),1);Lr(a.i,Elb(h6(a,b.d)),1)}}else{e=Pr(a.i,Elb(Wv(Smb(a.k,c),24).a));d+=a.g.a.Y()-e}return d}
function Keb(a){switch(a.e){case 0:return veb;case 1:return seb;case 2:return reb;case 3:return yeb;case 4:return xeb;case 5:return Deb;case 6:return Ceb;case 7:return web;case 8:return teb;case 9:return ueb;case 11:return Aeb;case 10:return zeb;default:return Beb;}}
function Leb(a){switch(a.e){case 0:return neb;case 1:return meb;case 2:return jeb;case 3:return ieb;case 4:return peb;case 5:return oeb;case 6:return Heb;case 7:return Geb;case 8:return leb;case 9:return keb;case 10:return Eeb;case 11:return qeb;default:return Feb;}}
function Meb(a){switch(a.e){case 0:return oeb;case 1:return Heb;case 2:return Geb;case 3:return neb;case 4:return meb;case 5:return jeb;case 6:return ieb;case 7:return peb;case 8:return leb;case 9:return keb;case 10:return Eeb;case 11:return qeb;default:return Feb;}}
function Neb(a){switch(a.e){case 0:return jeb;case 1:return ieb;case 2:return peb;case 3:return oeb;case 4:return Heb;case 5:return Geb;case 6:return neb;case 7:return meb;case 8:return leb;case 9:return keb;case 10:return Eeb;case 11:return qeb;default:return Feb;}}
function fcb(a){var b,c,d,e,f,g,h,i;c=(mp(),new wub);h=new Yub((Oh(),new opb(a.f)));for(g=(e=(new Snb(h.a)).a.bb().mb(),new Ynb(e));g.a.G();){f=(d=Wv(g.a.H(),21),Wv(d.yb(),9));if(!f){Fmb();break}i=a.i[f.k];b=Wv(rub(c,i),20);if(!b){b=new GU;tub(c,i,b)}b.ib(f)}return c}
function CS(a,b,c){var d,e,f;for(e=new Tob(a.b.a.b);e.a<e.c.c.length;){d=Wv(Rob(e),25);if(!b.D(d)){continue}f=Ixb(Yv(c.B(d)));if(f>0){!(tK(a.b.d)&&d.q.d)&&!(uK(a.b.d)&&d.q.b)&&(d.j.e-=0>f/2-0.5?0:f/2-0.5);!(tK(a.b.d)&&d.q.a)&&!(uK(a.b.d)&&d.q.c)&&(d.j.b+=0>f-1?0:f-1)}}}
function T6(a){var b,c,d;d=a.a.f;switch(a.b){case 0:return new Tob(a.a.f);case 1:return Pl((c=new W6(d),c),S6(a));case 2:switch(a.c.e){case 2:case 1:return Pl(new Tob(d),S6(a));case 3:case 4:return Pl((b=new W6(d),b),S6(a));}}throw new Imb('PortOrder not implemented.')}
function CT(a,b){var c;if(!!a.d&&(b.c!=a.e.c||hT(a.e.b,b.b))){vU(a.f,a.d);a.a=a.d.d+a.d.c;a.d=null;a.e=null}eT(b.b)?(a.c=b):(a.b=b);if(b.b==(cT(),$S)&&!b.a||b.b==_S&&b.a||b.b==aT&&b.a||b.b==bT&&!b.a){if(!!a.c&&!!a.b){c=new VN(a.a,a.c.d,b.c-a.a,a.b.d-a.c.d);a.d=c;a.e=b}}}
function Cbb(a,b,c,d){this.e=a;this.j=Wv(rJ(a,(Rib(),Kib)),134);this.f=xv(qB,Nzb,9,b,0,1);this.b=xv(HF,Txb,184,b,6,1);this.a=xv(qB,Nzb,9,b,0,1);this.d=xv(HF,Txb,184,b,6,1);this.i=xv(qB,Nzb,9,b,0,1);this.g=xv(HF,Txb,184,b,6,1);this.n=xv(HF,Txb,184,b,6,1);this.k=c;this.c=d}
function P6(a,b,c){var d,e;if(b.g==(CX(),BX)&&c.g==BX){if(!LM(Wv(rJ(Wv(rJ(b,(Rib(),uib)),9),(eM(),TL)),28))||Wv(rJ(b,uib),9)!=Wv(rJ(c,uib),9)){return}if(I6(b)||I6(c)){a.d=1;a.b=1;return}e=Wv(yU(b.f,0),7).g;d=Wv(yU(c.f,0),7).g;M6(b).g==(sN(),$M)?H6(a,b,c,e,d):H6(a,c,b,d,e)}}
function f7(a){if(!a.a.c||!a.a.d){throw new ulb((Gkb(QD),QD.j+' must have a source and target '+(Gkb(UD),UD.j)+' specified.'))}if(a.a.c==a.a.d){throw new ulb('Network simplex does not support self-loops: '+a.a+' '+a.a.c+' '+a.a.d)}o7(a.a.c.g,a.a);o7(a.a.d.c,a.a);return a.a}
function H6(a,b,c,d,e){if(d==(sN(),ZM)&&e==ZM){N6(a,b)>N6(a,c)?(a.d=K6(a,c)):(a.b=K6(a,b))}else if(d==rN&&e==rN){N6(a,b)<N6(a,c)?(a.d=K6(a,c)):(a.b=K6(a,b))}else if(d==rN&&e==ZM){if(N6(a,b)>N6(a,c)){a.d=K6(a,c);a.b=K6(a,b)}}else{if(N6(a,b)<N6(a,c)){a.d=K6(a,c);a.b=K6(a,b)}}}
function W1(a){var b,c,d,e,f,g,h,i;i=a.f.c.length;c=0;b=i;e=2*i;for(h=new Tob(a.f);h.a<h.c.c.length;){g=Wv(Rob(h),7);switch(g.g.e){case 2:case 4:g.k=-1;break;case 1:case 3:d=g.b.c.length;f=g.e.c.length;d>0&&f>0?(g.k=b++):d>0?(g.k=c++):f>0?(g.k=e++):(g.k=c++);}}Gpb(a.f,new Z1)}
function i0(a,b,c,d){var e,f,g,h,i;if(c.d.f==b.f){return}e=new uX(a);sX(e,(CX(),zX));sJ(e,(Rib(),uib),c);sJ(e,(eM(),TL),(KM(),FM));d.c[d.c.length]=e;g=new RX;PX(g,e);QX(g,(sN(),rN));h=new RX;PX(h,e);QX(h,ZM);i=c.d;eW(c,g);f=new hW;qJ(f,c);sJ(f,CL,null);dW(f,h);eW(f,i);j0(e,g,h)}
function W2(a){var b,c,d,e,f,g,h,i,j;g=rAb;i=rAb;h=null;for(c=new Sub(new Lub(a.e));c.b!=c.c.a.b;){b=Rub(c);if(Wv(b.d,60).c==1){d=Wv(b.e,116).a;j=Wv(b.e,116).b;e=g-d>uAb;f=d-g<uAb&&i-j>uAb;if(e||f){i=Wv(b.e,116).b;g=Wv(b.e,116).a;h=Wv(b.d,60);if(i==0&&g==0){return h}}}}return h}
function i1(a,b){var c,d,e,f,g,h;f=a.d;h=Wv(rJ(a,(eM(),dM)),15).a;if(h<0){h=0;sJ(a,dM,new llb(h))}b.j.b=h;g=Math.floor(h/2);d=new RX;QX(d,(sN(),rN));PX(d,b);d.i.b=g;e=new RX;QX(e,ZM);PX(e,b);e.i.b=g;eW(a,d);c=new hW;qJ(c,a);sJ(c,CL,null);dW(c,e);eW(c,f);h1(b,a,c);f1(a,c);return c}
function OZ(a){var b,c;c=Wv(rJ(a,(Mjb(),vjb)),85);b=Wv(rJ(a,(Rib(),mib)),140);if(c==(Xib(),Tib)){sJ(a,vjb,Wib);sJ(a,mib,(Hhb(),Ghb))}else if(c==Vib){sJ(a,vjb,Wib);sJ(a,mib,(Hhb(),Ehb))}else if(b==(Hhb(),Ghb)){sJ(a,vjb,Tib);sJ(a,mib,Fhb)}else if(b==Ehb){sJ(a,vjb,Vib);sJ(a,mib,Fhb)}}
function QO(a){var b,c,d,e,f;for(d=new Tob(zW(a.e));d.a<d.c.c.length;){c=Wv(Rob(d),129);f=new II(c.e.i);e=xO()[c.e.k];b=Wv(qsb(a.c,e),283);f.b=b.e+b.a;e.b==(DO(),BO)?(f.a=b.d):e.b==AO?(f.a=b.d+(b.c-c.e.j.a)/2):e.b==CO&&(f.a=b.d+b.c-c.e.j.a);c.e.i.a=f.a;c.e.i.b=f.b;b.a+=c.e.j.b+a.d}}
function UO(a){var b,c,d;for(c=new Tob(AW(a));c.a<c.c.c.length;){b=Wv(Rob(c),161);d=new II(b.e.i);switch(Wv(b.e,7).g.e){case 4:d.a=0;d.b=a.e.j.b/2;break;case 2:d.a=a.e.j.a;d.b=a.e.j.b/2;break;case 1:d.a=a.e.j.a/2;d.b=0;break;case 3:d.a=a.e.j.a/2;d.b=a.e.j.b;}b.e.i.a=d.a;b.e.i.b=d.b}}
function oV(){this.c=xv(kw,hyb,26,(sN(),Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN])).length,12,1);this.b=xv(kw,hyb,26,Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]).length,12,1);this.a=xv(kw,hyb,26,Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]).length,12,1);Yob(this.c,Uzb);Yob(this.b,Vzb);Yob(this.a,Vzb)}
function tfb(a,b,c){var d,e,f,g,h,i,j,k;f=Ixb(Yv(a.b.mb().H()));j=Ixb(Yv(rl(b.b)));d=CI(xI(a.a),j-c);e=CI(xI(b.a),c-f);k=vI(d,e);CI(k,1/(j-f));this.a=k;this.b=new GU;h=true;g=a.b.mb();g.H();while(g.G()){i=Ixb(Yv(g.H()));if(h&&i-c>RAb){this.b.ib(c);h=false}this.b.ib(i)}h&&this.b.ib(c)}
function G7(a){var b,c,d,e;J7(a,a.n);if(a.d.c.length>0){dpb(a.c);while(R7(a,Wv(Rob(new Tob(a.e.a)),61))<a.e.a.c.length){b=L7(a);e=b.d.e-b.c.e-b.a;b.d.j&&(e=-e);for(d=new Tob(a.e.a);d.a<d.c.c.length;){c=Wv(Rob(d),61);c.j&&(c.e+=e)}dpb(a.c)}dpb(a.c);O7(a,Wv(Rob(new Tob(a.e.a)),61));C7(a)}}
function Aab(a,b){var c,d,e,f,g,h,i;c=Vzb;h=(CX(),AX);for(e=new Tob(b.a);e.a<e.c.c.length;){d=Wv(Rob(e),9);f=d.g;if(f!=AX){g=Yv(rJ(d,(Rib(),wib)));if(g==null){c=c>0?c:0;d.i.b=c+Wjb(a.a,f,h)}else{d.i.b=(Dxb(g),g)}}i=Wjb(a.a,f,h);d.i.b<c+i+d.e.d&&(d.i.b=c+i+d.e.d);c=d.i.b+d.j.b+d.e.a;h=f}}
function mdb(a,b,c){var d,e,f;c.db(b,a);vU(a.g,b);f=a.o.d.Lc(b);hlb(a.k)?(a.k=f):(a.k=Qlb(a.k,f));hlb(a.a)?(a.a=f):(a.a=Nlb(a.a,f));b.g==a.o.d.Mc()?hdb(a.j,f):hdb(a.n,f);for(e=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[new fY(b),new lY(b)]))))));Cm(e);){d=Wv(Dm(e),7);c.R(d)||mdb(a,d,c)}}
function dlb(a){var b,c,d,e,f;d=(bmb(),a.length);e=d>0&&(a.charCodeAt(0)==45||a.charCodeAt(0)==43)?1:0;for(b=e;b<d;b++){if(Dkb(a.charCodeAt(b))==-1){throw new Ylb(dyb+a+'"')}}f=parseInt(a,10);c=f<eyb;if(isNaN(f)){throw new Ylb(dyb+a+'"')}else if(c||f>$xb){throw new Ylb(dyb+a+'"')}return f}
function H$(a,b,c,d){var e,f,g,h;e=Wv(nX(b,(sN(),rN)).mb().H(),7);f=Wv(nX(b,ZM).mb().H(),7);for(h=new Tob(a.f);h.a<h.c.c.length;){g=Wv(Rob(h),7);while(g.b.c.length!=0){eW(Wv(yU(g.b,0),12),e)}while(g.e.c.length!=0){dW(Wv(yU(g.e,0),12),f)}}c||sJ(b,(Rib(),qib),null);d||sJ(b,(Rib(),rib),null)}
function jU(a){var b,c,d,e,f,g,h;h=new $U;for(g=new Tob(a.b);g.a<g.c.c.length;){f=Wv(Rob(g),9);if(f.g==(CX(),xX)){continue}hU(h,f,new FI);for(e=Uh(mX(f));Cm(e);){d=Wv(Dm(e),12);if(d.c.f.g==xX||d.d.f.g==xX){continue}for(c=WI(d.a,0);c.b!=c.d.c;){b=Wv(_ub(c),10);ZU(h,new VS(b.a,b.b))}}}return h}
function X4(a,b,c,d){var e,f,g;this.e=new jJ;this.a=a;this.b=b;if(a.b<b.b){this.j=a.a;this.k=a.b;this.n=b.b}else{this.j=b.a;this.k=b.b;this.n=a.b}e=Wv(rJ(d,(eM(),CL)),44);if(e){for(g=WI(e,0);g.b!=g.d.c;){f=Wv(_ub(g),10);RR(f.a,a.a)&&QI(this.e,f)}}this.g=c;!!this.g&&(this.i=this.j-c.j.d);this.f=d}
function Zj(a){hi();var b,c,d,e,f,g;g=new Wub;zpb(g,a);for(c=(f=(new Snb(g.a)).a.bb().mb(),new Ynb(f));c.a.G();){b=(d=Wv(c.a.H(),21),d.yb());_b(b)}switch(g.a.Y()){case 0:return kr(),jr;case 1:return new Gr((e=(new Snb(g.a)).a.bb().mb(),d=Wv((new Ynb(e)).a.H(),21),d.yb()));default:return new lr(g);}}
function $P(a,b,c,d){var e,f,g;VP(a,c,'x',b.i.a+d.a);VP(a,c,'y',b.i.b+d.b);VP(a,c,Jzb,b.j.a);VP(a,c,Kzb,b.j.b);if(aw(b,9)){if(Wv(rJ(b,(eM(),bM)),86).kb((MN(),JN))){e=Wv(b,9).b;g=Pu(c,Lzb);if(!g){g=new Tu;Ru(c,Lzb,g)}f=g.kc();VP(a,f,'left',e.b);VP(a,f,'top',e.d);VP(a,f,'right',e.c);VP(a,f,Azb,e.a)}}}
function GR(a,b){var c,d,e,f,g,h,i,j,k,l;g=b==1?wR:vR;for(f=(i=(new Snb(g.a)).a.bb().mb(),new Ynb(i));f.a.G();){e=(h=Wv(f.a.H(),21),Wv(h.yb(),59));for(k=Wv(Dd(a.f.c,e),18).mb();k.G();){j=Wv(k.H(),27);d=Wv(j.b,25);l=Wv(j.a,78);c=l.c;switch(e.e){case 2:case 1:d.j.e+=c;break;case 4:case 3:d.j.d+=c;}}}}
function IS(a,b){var c,d,e;b.a?(Rwb(a.b,b.b),a.a[b.b.k]=Wv(Twb(a.b,b.b),25),c=Wv(Swb(a.b,b.b),25),!!c&&(a.a[c.k]=b.b),undefined):(d=Wv(Twb(a.b,b.b),25),!!d&&d==a.a[b.b.k]&&!!d.f&&d.f!=b.b.f&&d.i.ib(b.b),e=Wv(Swb(a.b,b.b),25),!!e&&a.a[e.k]==b.b&&!!e.f&&e.f!=b.b.f&&b.b.i.ib(e),Uwb(a.b,b.b),undefined)}
function p1(a,b){var c,d,e,f,g,h,i;e=new GU;for(c=0;c<=a.i;c++){d=new sY(b);d.k=a.i-c;e.c[e.c.length]=d}for(h=new Tob(a.o);h.a<h.c.c.length;){g=Wv(Rob(h),9);rX(g,Wv(yU(e,a.i-a.f[g.k]),16))}f=new Tob(e);while(f.a<f.c.c.length){i=Wv(Rob(f),16);i.a.c.length==0&&Sob(f)}b.c.c=xv(UF,syb,1,0,4,1);xU(b.c,e)}
function N4(a){var b,c,d,e;a.a.a.c=xv(UF,syb,1,0,4,1);for(d=new Tob(a.a.b);d.a<d.c.c.length;){b=Wv(Rob(d),25);b.f=null}for(e=new Tob(a.a.b);e.a<e.c.c.length;){b=Wv(Rob(e),25);!b.o&&vU(a.a.a,new QR(Bv(tv(kA,1),syb,25,0,[b])))}for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);!!b.o&&OR(b.o.f,b)}}
function fc(a,b){var c,d,e,f;a=(bmb(),a==null?Wxb:a);c=(a.length+16*b.length,new Amb);f=0;d=0;while(d<b.length){e=a.indexOf('%s',f);if(e==-1){break}jkb(c,a,f,e);xmb(c,b[d++]);f=e+2}wmb(c,a,f,a.length);if(d<b.length){c.a+=' [';xmb(c,b[d++]);while(d<b.length){c.a+=', ';xmb(c,b[d++])}c.a+=']'}return c.a}
function _vb(a,b,c,d){var e,f;if(!b){return c}else{e=a.a.$b(c.d,b.d);if(e==0){d.d=job(b,c.e);d.b=true;return b}f=e<0?0:1;b.a[f]=_vb(a,b.a[f],c,d);if(awb(b.a[f])){if(awb(b.a[1-f])){b.b=true;b.a[0].b=false;b.a[1].b=false}else{awb(b.a[f].a[f])?(b=hwb(b,1-f)):awb(b.a[f].a[1-f])&&(b=gwb(b,1-f))}}}return b}
function GY(a,b){var c,d,e,f,g,h,i,j,k,l;i=pmb(b.a);h=hw(Llb(i/a.a));l=b.a;g=0;j=h;for(f=0;f<a.a;++f){k=(bmb(),l.substr((0>g?0:g)<i?0>g?0:g:i,(0>(j<i?j:i)?0:j<i?j:i)-((0>g?0:g)<i?0>g?0:g:i)));g=j;j+=h;d=Wv(yU(a.c,f),9);c=new dX(k);c.j.b=b.j.b;Fd(a.b,b,c);vU(d.c,c)}BU(a.g.c,b);vU(a.i,(e=new PY(a,b),e))}
function p8(a,b,c){var d,e,f,g,h,i,j,k,l;b.k=1;f=b.d;for(l=oX(b,(djb(),bjb)).mb();l.G();){k=Wv(l.H(),7);for(e=new Tob(k.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);j=d.d.f;if(b!=j){g=j.d;if(g.k<=f.k){h=f.k+1;if(h==c.c.c.length){i=new sY(c);i.k=h;vU(c.c,i);rX(j,i)}else{i=Wv(yU(c.c,h),16);rX(j,i)}p8(a,j,c)}}}}}
function SO(a){var b,c,d,e,f;b=a.e.j;for(d=new Tob(AW(a));d.a<d.c.c.length;){c=Wv(Rob(d),161);e=Wv(oW(c,(eM(),LL)),15);!e&&(e=new llb(0));f=new II(c.e.i);switch(Wv(c.e,7).g.e){case 4:f.a=-c.e.j.a-e.a;break;case 2:f.a=b.a+e.a;break;case 1:f.b=-c.e.j.b-e.a;break;case 3:f.b=b.b+e.a;}c.e.i.a=f.a;c.e.i.b=f.b}}
function PZ(a){var b,c,d;d=Wv(rJ(a,(eM(),JL)),18);if(d.V()){return}c=(b=Wv(Hkb(Gz),11),new atb(b,Wv(exb(b,b.length),11),0));d.kb((oM(),jM))?Wsb(c,jM):Wsb(c,kM);d.kb(hM)||Wsb(c,hM);d.kb(gM)?Wsb(c,nM):d.kb(fM)?Wsb(c,mM):d.kb(iM)&&Wsb(c,lM);d.kb(nM)?Wsb(c,gM):d.kb(mM)?Wsb(c,fM):d.kb(lM)&&Wsb(c,iM);sJ(a,JL,c)}
function afb(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o;m=Zeb(a,c);for(i=0;i<b;i++){e.J(c);n=new GU;o=Wv(d.H(),92);for(k=m+i;k<a.c;k++){h=o;o=Wv(d.H(),92);vU(n,new tfb(h,o,c))}for(l=m+i;l<a.c;l++){d.M();l>m+i&&d.I()}for(g=new Tob(n);g.a<g.c.c.length;){f=Wv(Rob(g),92);d.J(f)}if(i<b-1){for(j=m+i;j<a.c;j++){d.M()}}}}
function CW(a){var b,c,d,e;if(a.d&&Wv(a.e,7).f.g==(CX(),BX)){return ypb(),ypb(),vpb}else if(!a.a){a.a=new GU;for(d=new Tob(Wv(a.e,7).b);d.a<d.c.c.length;){b=Wv(Rob(d),12);vU(a.a,new tW(b))}if(a.d){e=Wv(rJ(Wv(a.e,7),(Rib(),Bib)),9);if(e){for(c=Uh(iX(e));Cm(c);){b=Wv(Dm(c),12);vU(a.a,new tW(b))}}}}return a.a}
function EW(a){var b,c,d,e;if(a.d&&Wv(a.e,7).f.g==(CX(),BX)){return ypb(),ypb(),vpb}else if(!a.c){a.c=new GU;for(d=new Tob(Wv(a.e,7).e);d.a<d.c.c.length;){b=Wv(Rob(d),12);vU(a.c,new tW(b))}if(a.d){e=Wv(rJ(Wv(a.e,7),(Rib(),Bib)),9);if(e){for(c=Uh(mX(e));Cm(c);){b=Wv(Dm(c),12);vU(a.c,new tW(b))}}}}return a.c}
function N1(a,b){var c,d,e,f,g,h,i,j;h=Wv(rJ(a,(Rib(),uib)),7);i=MI(Bv(tv(qz,1),Fzb,10,0,[h.f.i,h.i,h.a])).a;j=a.f.i.b;c=Wv(FU(a.b,xv(dB,gAb,12,a.b.c.length,0,1)),47);for(e=0,f=c.length;e<f;++e){d=c[e];eW(d,h);SI(d.a,new HI(i,j));if(b){g=Wv(rJ(d,(eM(),CL)),44);if(!g){g=new jJ;sJ(d,CL,g)}QI(g,new HI(i,j))}}}
function O1(a,b){var c,d,e,f,g,h,i,j;e=Wv(rJ(a,(Rib(),uib)),7);i=MI(Bv(tv(qz,1),Fzb,10,0,[e.f.i,e.i,e.a])).a;j=a.f.i.b;c=Wv(FU(a.e,xv(dB,gAb,12,a.e.c.length,0,1)),47);for(g=0,h=c.length;g<h;++g){f=c[g];dW(f,e);RI(f.a,new HI(i,j));if(b){d=Wv(rJ(f,(eM(),CL)),44);if(!d){d=new jJ;sJ(f,CL,d)}QI(d,new HI(i,j))}}}
function X2(a){var b,c,d,e,f,g,h,i,j;g=rAb;i=rAb;h=null;for(c=new Sub(new Lub(a.e));c.b!=c.c.a.b;){b=Rub(c);if(gw(b.d)===gw((Ieb(),keb))||gw(b.d)===gw(leb)){d=Wv(b.e,116).a;j=Wv(b.e,116).b;e=g-d>uAb;f=d-g<uAb&&i-j>uAb;if(e||f){i=Wv(b.e,116).b;g=Wv(b.e,116).a;h=Wv(b.d,60);if(i==0&&g==0){return h}}}}return h}
function P4(a,b){var c,d,e,f,g;a.d=b;Ymb(a.b);a.c=false;h:for(d=new Tob(a.d.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);for(f=new Tob(c.a);f.a<f.c.c.length;){e=Wv(Rob(f),9);if(!sl(gX(e))){a.c=true;break h}}}g=Vsb((sK(),qK),Bv(tv(Bz,1),uyb,59,0,[oK,pK]));if(!a.c){Wsb(g,rK);Wsb(g,nK)}a.a=new NR(g);O4(a);return a.a}
function $2(){var a,b,c,d,e;this.e=(mp(),new wub);this.b=(c=Wv(Hkb(_E),11),new atb(c,Wv(exb(c,c.length),11),0));this.c=(d=Wv(Hkb(_E),11),new atb(d,Wv(exb(d,d.length),11),0));this.a=(e=Wv(Hkb(_E),11),new atb(e,Wv(exb(e,e.length),11),0));for(b=(Ieb(),Ieb(),feb).mb();b.G();){a=Wv(b.H(),60);tub(this.e,a,new _2)}}
function gdb(a,b,c){var d,e,f,g,h,i;if(Jlb(a.k-a.a)<dAb||Jlb(b.k-b.a)<dAb){return}d=edb(a.n,b.j,c);e=edb(b.n,a.j,c);f=fdb(a.n,b.k,b.a)+fdb(b.j,a.k,a.a);g=fdb(b.n,a.k,a.a)+fdb(a.j,b.k,b.a);h=16*d+f;i=16*e+g;if(h<i){new kdb(a,b,i-h)}else if(h>i){new kdb(b,a,h-i)}else if(h>0&&i>0){new kdb(a,b,0);new kdb(b,a,0)}}
function c3(a,b){var c,d,e,f,g,h,i,j,k;j=new GU;k=null;for(d=Wv(qsb(a3,a),20).mb();d.G();){c=Wv(d.H(),75);for(i=(f=(new Snb(c.c.a)).a.bb().mb(),new Ynb(f));i.a.G();){g=(e=Wv(i.a.H(),21),Wv(e.yb(),7));Anb(b,g);J2(g,a.b)}xU(j,c.b);k=a.a}Dpb(j);K2(j,k);for(h=new Tob(j);h.a<h.c.c.length;){g=Wv(Rob(h),7);Anb(b,g)}}
function GP(){var b={'layout':function(a){Rxb(IP(a))}};if(typeof klayregister===Zxb){klayregister(b)}else{typeof document!==Czb&&($wnd.$klay=b);"object"===Sxb&&module.exports&&(module.exports=b);typeof document===Czb&&typeof self!==Czb&&self.addEventListener('message',function(a){b.layout(a.data)},false)}}
function _cb(a,b,c,d,e){var f,g,h;h=e?d.b:d.a;if(h>c.k&&h<c.a||c.j.b!=0&&c.n.b!=0&&(Jlb(h-Ixb(Yv(UI(c.j))))<dAb&&Jlb(h-Ixb(Yv(UI(c.n))))<dAb||Jlb(h-Ixb(Yv(VI(c.j))))<dAb&&Jlb(h-Ixb(Yv(VI(c.n))))<dAb)){if(!ttb(a.b,d)){g=Wv(rJ(b,(eM(),CL)),44);if(!g){g=new jJ;sJ(b,CL,g)}f=new II(d);TI(g,f,g.c.b,g.c);stb(a.b,f)}}}
function lU(a,b,c){var d,e,f,g,h,i,j,k,l;d=c.c;e=c.d;h=MX(b.c);i=MX(b.d);if(d==b.c){h=mU(a,h,e);i=nU(b.d)}else{h=nU(b.c);i=mU(a,i,e)}j=new kJ(b.a);TI(j,h,j.a,j.a.a);TI(j,i,j.c.b,j.c);g=b.c==d;l=new pV;for(f=0;f<j.b-1;++f){k=new RJ(Wv(tn(j,f),10),Wv(tn(j,f+1),10));g&&f==0||!g&&f==j.b-2?(l.b=k):vU(l.a,k)}return l}
function GW(a,b){var c,d,e,f;f=a.g.e-b.g.e;if(f!=0){return f}c=Wv(rJ(a,(eM(),UL)),24);d=Wv(rJ(b,UL),24);if(!!c&&!!d){e=c.a-d.a;if(e!=0){return e}}switch(a.g.e){case 1:return glb(a.i.a,b.i.a);case 2:return glb(a.i.b,b.i.b);case 3:return glb(b.i.a,a.i.a);case 4:return glb(b.i.b,a.i.b);default:throw new ulb(iAb);}}
function KO(a,b){var c,d,e,f,g;g=new FI;for(f=new Tob(AW(a));f.a<f.c.c.length;){e=Wv(Rob(f),161);switch(Wv(e.e,7).g.e){case 4:case 2:g.b=Nlb(g.b,e.e.i.b+e.e.j.b+(b?(d=Wv(e.e,7).d,new EP(d.d,d.b,d.a,d.c)).a:0));break;case 1:case 3:g.a=Nlb(g.a,e.e.i.a+e.e.j.a+(b?(c=Wv(e.e,7).d,new EP(c.d,c.b,c.a,c.c)).c:0));}}return g}
function d3(a,b){var c,d,e,f,g,h,i;e=new GU;i=new GU;c=Wv(qsb(a3,a),20).mb();while(c.G()){d=Wv(c.H(),75);wU(e,d.b);wU(e,$db(d));if(c.G()){d=Wv(c.H(),75);xU(i,$db(d));xU(i,d.b)}}K2(e,a.b);K2(i,a.a);for(h=new Tob(e);h.a<h.c.c.length;){f=Wv(Rob(h),7);Anb(b,f)}for(g=new Tob(i);g.a<g.c.c.length;){f=Wv(Rob(g),7);Anb(b,f)}}
function ohb(){ohb=iI;fhb=new phb('COMMENTS',0);hhb=new phb('EXTERNAL_PORTS',1);ihb=new phb('HYPEREDGES',2);jhb=new phb('HYPERNODES',3);khb=new phb('NON_FREE_PORTS',4);lhb=new phb('NORTH_SOUTH_PORTS',5);nhb=new phb('SELF_LOOPS',6);ehb=new phb('CENTER_LABELS',7);ghb=new phb('END_LABELS',8);mhb=new phb('PARTITIONS',9)}
function Jxb(a,b){var c,d,e,f;a=(bmb(),a==null?Wxb:a);c=(a.length+16*b.length,new Amb);f=0;d=0;while(d<b.length){e=a.indexOf('%s',f);if(e==-1){break}ymb(c,a.substr(f,e-f));xmb(c,b[d++]);f=e+2}ymb(c,imb(a,f,a.length-f));if(d<b.length){c.a+=' [';xmb(c,b[d++]);while(d<b.length){c.a+=', ';xmb(c,b[d++])}c.a+=']'}return c.a}
function pX(a,b,c){var d,e;e=null;switch(b.e){case 1:e=(LX(),GX);break;case 2:e=(LX(),IX);}d=null;switch(c.e){case 1:d=(LX(),HX);break;case 2:d=(LX(),FX);break;case 3:d=(LX(),JX);break;case 4:d=(LX(),KX);}return !!e&&!!d?pl(a.f,(hc(),new ic(new opb(Bv(tv(tw,1),syb,68,0,[Wv(_b(e),68),Wv(_b(d),68)]))))):(ypb(),ypb(),vpb)}
function vY(a,b,c){var d,e,f,g,h,i,j;i=Eo(mX(b));for(e=WI(i,0);e.b!=e.d.c;){d=Wv(_ub(e),12);j=d.d.f;if(!(Ckb(Ixb(Xv(rJ(j,(Rib(),Vhb)))))&&rJ(j,uib)!=null)&&j.g==(CX(),wX)&&!Ckb(Ixb(Xv(rJ(d,Iib))))&&d.d.g==(sN(),rN)){f=rY(j.d)-rY(b.d);if(f>1){c?(g=rY(b.d)+1):(g=rY(j.d)-1);h=Wv(yU(a.a.c,g),16);rX(j,h)}vY(a,j,c)}}return b}
function Hcb(a,b){var c,d,e,f;b.d?(e=a.a.c==(Gbb(),Fbb)?iX(b.b):mX(b.b)):(e=a.a.c==(Gbb(),Ebb)?iX(b.b):mX(b.b));f=false;for(d=(Il(),new Im(Dl(ul(e.a,new yl))));Cm(d);){c=Wv(Dm(d),12);if(a.c.a[c.c.f.d.k]===a.c.a[c.d.f.d.k]){continue}f=true;if(ttb(a.b,a.a.f[zcb(c,b.b).k])){b.c=true;b.a=c;return b}}b.c=f;b.a=null;return b}
function K4(a,b,c){var d,e,f,g;d=Wv(rJ(a.d,(eM(),pL)),15).a;for(f=new Tob(a.a.b);f.a<f.c.c.length;){e=Wv(Rob(f),25);if(aw(e,93)){g=Wv(e,93).b;if(g.g==(CX(),xX)){switch(Wv(rJ(g,(Rib(),hib)),32).e){case 4:g.i.a=b.a-d;break;case 2:g.i.a=c.a+d-(g.j.a+g.e.c);break;case 1:g.i.b=b.b-d;break;case 3:g.i.b=c.b+d-(g.j.b+g.e.a);}}}}}
function Ztb(){if(!Object.create||!Object.getOwnPropertyNames){return false}var a='__proto__';var b=Object.create(null);if(b[a]!==undefined){return false}var c=Object.getOwnPropertyNames(b);if(c.length!=0){return false}b[a]=42;if(b[a]!==42){return false}if(Object.getOwnPropertyNames(b).length==0){return false}return true}
function eS(a){var b,c,d,e,f,g,h,i,j;for(g=new Tob(a.a.a);g.a<g.c.c.length;){e=Wv(Rob(g),78);e.f=0;e.e.a.Q()}for(f=new Tob(a.a.a);f.a<f.c.c.length;){e=Wv(Rob(f),78);for(c=(j=(new Snb(e.a.a)).a.bb().mb(),new Ynb(j));c.a.G();){b=(d=Wv(c.a.H(),21),Wv(d.yb(),25));for(i=b.i.mb();i.G();){h=Wv(i.H(),25);if(h.f!=e){stb(e.e,h);++h.f.f}}}}}
function bcb(a,b,c,d){var e,f,g,h;if(b.g==(CX(),wX)){for(f=Uh(iX(b));Cm(f);){e=Wv(Dm(f),12);g=e.c.f;if((g.g==wX||Ckb(Ixb(Xv(rJ(g,(Rib(),Vhb))))))&&a.d.a[e.c.f.d.k]==d&&a.d.a[b.d.k]==c){return true}}}if(b.g==zX){for(f=Uh(iX(b));Cm(f);){e=Wv(Dm(f),12);h=e.c.f.g;if(h==zX&&a.d.a[e.c.f.d.k]==d&&a.d.a[b.d.k]==c){return true}}}return false}
function cfb(a){var b,c,d,e,f,g;e=a.g.tb();d=a.b.tb();if(a.e){for(c=0;c<a.c;c++){e.H()}}else{for(c=0;c<a.c-1;c++){e.H();e.I()}}b=Ixb(Yv(e.H()));while(a.i-b>RAb){f=b;g=0;while((b-f<=0?0-(b-f):b-f)<RAb){++g;b=Ixb(Yv(e.H()));d.H()}if(g<a.c){e.M();afb(a,a.c-g,f,d,e);e.H()}d.M()}if(!a.e){for(c=0;c<a.c-1;c++){e.H();e.I()}}a.e=true;a.d=true}
function O2(a){var b,c,d,e;switch(V2(a.a).c){case 4:return Ieb(),oeb;case 3:return Wv(S2(a.a).mb().H(),60);case 2:d=V2(a.a);c=new jtb(d);b=Wv(itb(c),60);e=Wv(itb(c),60);return Meb(b)==e?Zsb(d,(Ieb(),oeb))?ieb:oeb:Leb(Leb(b))==e?Leb(b):Neb(b);case 1:d=V2(a.a);return Meb(Wv(itb(new jtb(d)),60));case 0:return Ieb(),peb;default:return null;}}
function Q3(a,b){var c;oR.call(this);this.a=Wv(rJ(b,(Rib(),Jib)),15).a;this.c=this.a*Wv(rJ(b,(Mjb(),Ejb)),15).a;this.b=a;this.j=new VN(a.i.a-a.e.b,a.i.b-a.e.d,a.j.a+a.e.b+a.e.c,a.j.b+a.e.d+a.e.a);BI(this.g);c=tl(iX(a))-tl(mX(a));c<0?vS(this.n,true,(sK(),oK)):c>0&&vS(this.n,true,(sK(),pK));a.g==(CX(),xX)&&wS(this.n,false,false,false,false)}
function UT(a,b,c){var d,e,f,g,h,i,j,k,l,m;f=new HI(b,c);for(k=new Tob(a.b);k.a<k.c.c.length;){j=Wv(Rob(k),9);vI(j.i,f);for(m=new Tob(j.f);m.a<m.c.c.length;){l=Wv(Rob(m),7);for(e=new Tob(l.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);hJ(d.a,f);g=Wv(rJ(d,(eM(),CL)),44);!!g&&hJ(g,f);for(i=new Tob(d.b);i.a<i.c.c.length;){h=Wv(Rob(i),33);vI(h.i,f)}}}}}
function TW(a,b,c){var d,e,f,g,h,i,j,k,l,m;f=new HI(b,c);for(k=new Tob(a.b);k.a<k.c.c.length;){j=Wv(Rob(k),9);vI(j.i,f);for(m=new Tob(j.f);m.a<m.c.c.length;){l=Wv(Rob(m),7);for(e=new Tob(l.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);hJ(d.a,f);g=Wv(rJ(d,(eM(),CL)),44);!!g&&hJ(g,f);for(i=new Tob(d.b);i.a<i.c.c.length;){h=Wv(Rob(i),33);vI(h.i,f)}}}}}
function X0(a,b){var c,d,e,f,g;for(g=new Tob(a.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);if(b){if(f.b.c.length!=0){throw new $J((e=lX(a),nAb+(e==null?Dlb(a.k):e)+oAb+pAb+qAb))}}else{for(d=new Tob(f.b);d.a<d.c.c.length;){c=Wv(Rob(d),12);if(gw(rJ(c.c.f,(Mjb(),vjb)))!==gw((Xib(),Tib))){throw new $J((e=lX(a),nAb+(e==null?Dlb(a.k):e)+oAb+pAb+qAb))}}}}}
function y6(a,b,c){var d,e,f,g,h,i,j;d=0;j=nX(b,c);for(i=j.mb();i.G();){h=Wv(i.H(),7);if(Wv(rJ(h,(Rib(),Bib)),9)){g=Wv(rJ(h,Bib),9);nX(g,(sN(),ZM)).mb().G()&&(d+=(f=a.k?1:NX(Wv(yU(g.f,0),7)),f*Slb(w6(a,b,c).a-1-Wv(Smb(a.i,h),24).a,B6(a,b,g))));nX(g,rN).mb().G()&&(d+=(e=a.k?1:NX(Wv(yU(g.f,0),7)),e*Slb(Wv(Smb(a.i,h),24).a,B6(a,b,g))))}}return d}
function J7(a,b){var c,d,e,f,g,h,i;e=xv(mw,Yyb,26,a.e.a.c.length,12,1);for(g=new Tob(a.e.a);g.a<g.c.c.length;){f=Wv(Rob(g),61);e[f.b]+=f.c.c.length}h=Eo(b);while(h.b!=0){f=Wv(h.b==0?null:(Bxb(h.b!=0),$I(h,h.a.a)),61);for(d=new Tob(f.g);d.a<d.c.c.length;){c=Wv(Rob(d),89);i=c.d;i.e=Plb(i.e,f.e+c.a);--e[i.b];e[i.b]==0&&(TI(h,i,h.c.b,h.c),true)}}}
function nP(a,b,c,d,e,f,g){a.d=d.e.i.a;a.e=d.e.i.b;if(e){a.d+=e.e.i.a;a.e+=e.e.i.b}a.c=b.e.j.a;a.b=b.e.j.b;if(!e){c?(a.d-=g+b.e.j.a):(a.d+=d.e.j.a+g)}else{switch(Wv(e.e,7).g.e){case 0:case 2:a.d+=e.e.j.a+g+f.a+g;break;case 4:a.d-=g+f.a+g+b.e.j.a;break;case 1:a.d+=e.e.j.a+g;a.e-=g+f.b+g+b.e.j.b;break;case 3:a.d+=e.e.j.a+g;a.e+=e.e.j.b+g+f.b+g;}}}
function V9(a,b){var c,d,e,f,g,h,i,j,k;e=new GU;for(i=new Tob(b);i.a<i.c.c.length;){f=Wv(Rob(i),9);vU(e,a.b[f.d.k][f.k])}S9(a,e);while(k=T9(e)){U9(a,Wv(k.a,102),Wv(k.b,102),e)}b.c=xv(UF,syb,1,0,4,1);for(d=new Tob(e);d.a<d.c.c.length;){c=Wv(Rob(d),102);for(g=c.d,h=0,j=g.length;h<j;++h){f=g[h];b.c[b.c.length]=f;a.a[f.d.k][f.k].a=W9(c.g,c.d[0]).a}}}
function lS(a){var b,c,d,e,f,g,h;h=(mp(),new ntb);for(d=new Tob(a.a.b);d.a<d.c.c.length;){b=Wv(Rob(d),25);Umb(h,b,new GU)}for(e=new Tob(a.a.b);e.a<e.c.c.length;){b=Wv(Rob(e),25);b.r=Vzb;for(g=b.i.mb();g.G();){f=Wv(g.H(),25);Wv(re(Ktb(h.d,f)),20).ib(b)}}for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);b.i.Q();b.i=Wv(re(Ktb(h.d,b)),20)}eS(a)}
function kU(a){var b,c,d,e,f;e=Wv(yU(a.b,0),9);b=new uX(a);vU(a.b,b);b.j.a=Nlb(1,e.j.a);b.j.b=Nlb(1,e.j.b);b.i.a=e.i.a;b.i.b=e.i.b;switch(Wv(rJ(e,(Rib(),hib)),32).e){case 4:b.i.a+=2;break;case 1:b.i.b+=2;break;case 2:b.i.a-=2;break;case 3:b.i.b-=2;}d=new RX;PX(d,b);c=new hW;f=Wv(yU(e.f,0),7);dW(c,f);eW(c,d);vI(BI(d.i),f.i);vI(BI(d.a),f.a);return b}
function T8(a){var b,c,d,e,f,g,h,i,j;j=(mp(),new ntb);b=0;c=new l7;for(h=a.mb();h.G();){f=Wv(h.H(),9);i=x7(z7(y7(new A7,b++),f),c);Ltb(j.d,f,i)}for(g=a.mb();g.G();){f=Wv(g.H(),9);for(e=Uh(mX(f));Cm(e);){d=Wv(Dm(e),12);if(bW(d)){continue}f7(i7(h7(g7(j7(new k7,Plb(1,Wv(rJ(d,(Rib(),Eib)),24).a)),1),Wv(Smb(j,d.c.f),61)),Wv(Smb(j,d.d.f),61)))}}return c}
function E2(a){var b,c;if(a.V()){return}c=Wv(a.sb(0),75).f;new g3(a);b=new Fnb(c.f,0);e3((Ieb(),neb),b);f3(Eeb,b);D2((sN(),$M),b);d3(meb,b);f3(qeb,b);c3(jeb,b);e3(keb,b);D2(ZM,b);d3(ieb,b);e3(leb,b);c3(peb,b);e3(qeb,b);D2(pN,b);d3(oeb,b);e3(Eeb,b);c3(Heb,b);f3(leb,b);while(b.b<b.d.Y()){Bxb(b.b<b.d.Y());b.d.sb(b.c=b.b++)}d3(Geb,b);f3(keb,b);f3(neb,b)}
function F2(a){var b,c;if(a.V()){return}c=Wv(a.sb(0),75).f;new g3(a);b=new Fnb(c.f,0);e3((Ieb(),neb),b);f3(Eeb,b);D2((sN(),$M),b);c3(meb,b);f3(qeb,b);c3(jeb,b);e3(keb,b);D2(ZM,b);c3(ieb,b);e3(leb,b);c3(peb,b);e3(qeb,b);D2(pN,b);c3(oeb,b);e3(Eeb,b);c3(Heb,b);f3(leb,b);while(b.b<b.d.Y()){Bxb(b.b<b.d.Y());b.d.sb(b.c=b.b++)}c3(Geb,b);f3(keb,b);f3(neb,b)}
function N7(a){var b,c,d,e,f,g,h,i,j;e=eyb;g=$xb;for(j=new Tob(a.e.a);j.a<j.c.c.length;){h=Wv(Rob(j),61);g=Slb(g,h.e);e=Plb(e,h.e)}f=0;d=xv(mw,Yyb,26,e-g+1,12,1);for(i=new Tob(a.e.a);i.a<i.c.c.length;){h=Wv(Rob(i),61);h.e-=g;++d[h.e]}if(a.k){for(c=new Tob(a.k.c);c.a<c.c.c.length;){b=Wv(Rob(c),16);d[f++]+=b.a.c.length;if(d.length==f){break}}}return d}
function L4(a){var b,c,d,e;M4(a);J4(a);e=new HI(Uzb,Uzb);b=new HI(Vzb,Vzb);for(d=new Tob(a.a.b);d.a<d.c.c.length;){c=Wv(Rob(d),25);e.a=Qlb(e.a,c.j.d);e.b=Qlb(e.b,c.j.e);b.a=Nlb(b.a,c.j.d+c.j.c);b.b=Nlb(b.b,c.j.e+c.j.b)}vI(BI(a.d.d),zI(new HI(e.a,e.b)));vI(BI(a.d.e),EI(new HI(b.a,b.b),e));K4(a,e,b);a.a.a.c=xv(UF,syb,1,0,4,1);a.a.b.c=xv(UF,syb,1,0,4,1)}
function j1(a,b){var c,d,e,f,g,h,i,j,k,l;g=a.e;k=Wv(rJ(a,(Rib(),Qib)),20);l=0;if(k){i=0;for(f=k.mb();f.G();){e=Wv(f.H(),9);i=Nlb(i,e.j.b);l+=e.j.a}l+=b/2*(k.Y()-1);g.d+=i+b}c=Wv(rJ(a,Yhb),20);d=0;if(c){i=0;for(f=c.mb();f.G();){e=Wv(f.H(),9);i=Nlb(i,e.j.b);d+=e.j.a}d+=b/2*(c.Y()-1);g.a+=i+b}h=l>d?l:d;if(h>a.j.a){j=(h-a.j.a)/2;g.b=Nlb(g.b,j);g.c=Nlb(g.c,j)}}
function ST(a,b,c,d){var e,f,g,h,i,j,k,l,m,n;g=uI(b.d,c,d);for(l=new Tob(b.b);l.a<l.c.c.length;){k=Wv(Rob(l),9);vI(k.i,g);for(n=new Tob(k.f);n.a<n.c.c.length;){m=Wv(Rob(n),7);for(f=new Tob(m.e);f.a<f.c.c.length;){e=Wv(Rob(f),12);hJ(e.a,g);h=Wv(rJ(e,(eM(),CL)),44);!!h&&hJ(h,g);for(j=new Tob(e.b);j.a<j.c.c.length;){i=Wv(Rob(j),33);vI(i.i,g)}}}vU(a.b,k);k.a=a}}
function Q8(a,b){var c,d,e,f,g;a.c==null||a.c.length<b.c.length?(a.c=xv(KH,xAb,26,b.c.length,13,1)):dpb(a.c);a.a=new GU;d=0;for(g=new Tob(b);g.a<g.c.c.length;){e=Wv(Rob(g),9);e.k=d++}c=new aJ;for(f=new Tob(b);f.a<f.c.c.length;){e=Wv(Rob(f),9);if(!a.c[e.k]){R8(a,e);c.b==0||(Bxb(c.b!=0),Wv(c.a.a.c,20)).Y()<a.a.c.length?RI(c,a.a):SI(c,a.a);a.a=new GU}}return c}
function xfb(a,b,c){var d,e,f,g,h,i,j,k,l;d=sgb(a.g);j=vI(xI(a.i),a.a);k=vI(xI(b.i),b.a);e=vI(new II(j),CI(new GI(d),c));l=vI(new II(k),CI(new GI(d),c));g=CI(EI(new II(e),l),0.5);i=vI(vI(new II(l),g),CI(new GI(d),Tlb(g.a*g.a+g.b*g.b)));h=new ufb(Bv(tv(qz,1),Fzb,10,0,[j,e,i,l,k]));f=$eb(h,0.5,false);h.a=f;bfb(h,new Ffb(Bv(tv(qz,1),Fzb,10,0,[f,j,k])));return h}
function F7(a,b){var c,d,e,f,g;nI(b,'Network simplex',1);if(a.e.a.c.length<1){pI(b);return}for(f=new Tob(a.e.a);f.a<f.c.c.length;){e=Wv(Rob(f),61);e.e=0}g=a.e.a.c.length>=40;g&&Q7(a);H7(a);G7(a);c=K7(a);d=0;while(!!c&&d<a.f){E7(a,c,D7(a,c));c=K7(a);++d}g&&P7(a);a.a?B7(a,N7(a)):N7(a);a.b=null;a.d=null;a.p=null;a.c=null;a.g=null;a.i=null;a.n=null;a.o=null;pI(b)}
function uQ(a){var b,c,d,e,f,g,h,i,j,k;j=new vtb;e=(mp(),new ntb);for(h=0,i=a.length;h<i;++h){g=a[h];b=g.mc();j.a.db(b,j);b==null?Ltb(e.d,null,g):dub(e.e,b,g);k=gmb(b,(bmb(),b.lastIndexOf('.'))+1,b.length);if(!ttb(sQ,k)){j.a.db(k,j);k==null?Ltb(e.d,null,g):dub(e.e,k,g);stb(sQ,k)}}d=(hi(),Yj((f=(new Snb(j.a)).a.bb().mb(),new Ynb(f))));c=tj(e);return new RJ(d,c)}
function E7(a,b,c){var d,e,f;if(!b.e){throw new slb('Given leave edge is no tree edge.')}if(c.e){throw new slb('Given enter edge is a tree edge already.')}b.e=false;utb(a.p,b);c.e=true;stb(a.p,c);d=c.d.e-c.c.e-c.a;I7(a,c.d,b)||(d=-d);for(f=new Tob(a.e.a);f.a<f.c.c.length;){e=Wv(Rob(f),61);I7(a,e,b)||(e.e+=d)}a.j=1;dpb(a.c);O7(a,Wv(Rob(new Tob(a.e.a)),61));C7(a)}
function dU(a,b){var c,d,e,f,g,h,i,j,k,l,m,n;if(a.V()){return new FI}j=0;l=0;for(e=a.mb();e.G();){d=Wv(e.H(),55);f=d.e;j=Nlb(j,f.a);l+=f.a*f.b}j=Nlb(j,Math.sqrt(l)*Wv(rJ(Wv(a.mb().H(),55),(Rib(),Rhb)),15).a);m=0;n=0;i=0;c=b;for(h=a.mb();h.G();){g=Wv(h.H(),55);k=g.e;if(m+k.a>j){m=0;n+=i+b;i=0}UT(g,m,n);c=Nlb(c,m+k.a);i=Nlb(i,k.b);m+=k.a+b}return new HI(c+b,n+i+b)}
function Nm(a,b,c,d){var e,f,g;g=new Sn(b,c);if(!a.a){a.a=a.e=g;Umb(a.b,b,new Rn(g));++a.c}else if(!d){a.e.b=g;g.d=a.e;a.e=g;e=Wv(Smb(a.b,b),126);if(!e){Umb(a.b,b,new Rn(g));++a.c}else{++e.a;f=e.c;f.c=g;g.e=f;e.c=g}}else{e=Wv(Smb(a.b,b),126);++e.a;g.d=d.d;g.e=d.e;g.b=d;g.c=d;!d.e?(Wv(Smb(a.b,b),126).b=g):(d.e.c=g);!d.d?(a.a=g):(d.d.b=g);d.d=g;d.e=g}++a.d;return g}
function hS(a){var b,c,d,e,f,g,h,i;if(a.e){throw new ulb((Gkb(nA),'The '+nA.j+Yzb))}a.d==(sK(),qK)&&gS(a,oK);for(c=new Tob(a.a.a);c.a<c.c.c.length;){b=Wv(Rob(c),78);b.f=0}for(g=new Tob(a.a.b);g.a<g.c.c.length;){f=Wv(Rob(g),25);f.r=Vzb;for(e=f.i.mb();e.G();){d=Wv(e.H(),25);++d.f.f}}a.b.Cc(a);for(i=new Tob(a.a.b);i.a<i.c.c.length;){h=Wv(Rob(i),25);h.p=true}return a}
function V1(a,b,c,d,e){var f,g,h,i;f=new uX(a);sX(f,(CX(),BX));sJ(f,(eM(),TL),(KM(),FM));sJ(f,(Rib(),uib),b.c.f);g=new RX;sJ(g,uib,b.c);QX(g,e);PX(g,f);sJ(b.c,Bib,f);h=new uX(a);sX(h,BX);sJ(h,TL,FM);sJ(h,uib,b.d.f);i=new RX;sJ(i,uib,b.d);QX(i,e);PX(i,h);sJ(b.d,Bib,h);dW(b,g);eW(b,i);Fxb(0,c.c.length);fxb(c.c,0,f);d.c[d.c.length]=h;sJ(f,aib,Elb(1));sJ(h,aib,Elb(1))}
function j2(a,b){var c,d,e,f,g;g=Wv(rJ(a.f,(eM(),TL)),28);f=a.g.e-b.g.e;if(f!=0||g==(KM(),HM)){return f}if(g==(KM(),EM)){c=Wv(rJ(a,UL),24);d=Wv(rJ(b,UL),24);if(!!c&&!!d){e=c.a-d.a;if(e!=0){return e}}}switch(a.g.e){case 1:return glb(a.i.a,b.i.a);case 2:return glb(a.i.b,b.i.b);case 3:return glb(b.i.a,a.i.a);case 4:return glb(b.i.b,a.i.b);default:throw new ulb(iAb);}}
function hfb(a){var b,c,d,e,f,g,h,i,j,k,l;h=new GU;f=Ixb(Yv(a.g.sb(a.g.Y()-1)));for(l=a.g.mb();l.G();){k=Yv(l.H());uU(h,0,f-(Dxb(k),k))}g=lJ(Xeb(a));j=new GU;e=new Tob(h);i=new GU;for(b=0;b<a.c-1;b++){vU(j,Yv(Rob(e)))}for(d=WI(g,0);d.b!=d.d.c;){c=Wv(_ub(d),10);vU(j,Yv(Rob(e)));vU(i,new sfb(c,j));Cxb(0,j.c.length);j.c.splice(0,1)}return new ffb(a.e,a.f,a.d,a.c,h,i)}
function zs(a,b,c,d,e){var f,g,h,i,j;f=b.$b(c,a.b);if(f<0){h=a.e;if(!h){e[0]=0;return As(a,c,d)}g=h.d;a.e=zs(h,b,c,d,e);e[0]==0&&++a.a;a.j=PH(a.j,d);return a.e.d==g?a:Gs(a)}else if(f>0){i=a.g;if(!i){e[0]=0;return Bs(a,c,d)}g=i.d;a.g=zs(i,b,c,d,e);e[0]==0&&++a.a;a.j=PH(a.j,d);return a.g.d==g?a:Gs(a)}e[0]=a.c;j=PH(a.c,d);Xb(RH(j,$xb)<=0);a.c+=d;a.j=PH(a.j,d);return a}
function iJ(b,c){var d,e,f,g,h,i;f=fmb(c,',|;|\\(|\\)|\\[|\\]|\\{|\\}| |\t|\n');_I(b);try{e=0;h=0;g=0;i=0;while(e<f.length){if(f[e]!=null&&pmb(hmb(f[e]))>0){h%2==0?(g=clb(f[e])):(i=clb(f[e]));h>0&&h%2!=0&&QI(b,new HI(g,i));++h}++e}}catch(a){a=OH(a);if(aw(a,130)){d=a;throw new slb('The given string does not match the expected format for vectors.'+d)}else throw NH(a)}}
function _bb(a,b,c){var d,e,f,g,h,i,j,k;e=true;for(g=new Tob(b.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);j=Vzb;for(i=new Tob(f.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);k=Ixb(c.n[h.k])+Ixb(c.d[h.k])-h.e.d;d=Ixb(c.n[h.k])+Ixb(c.d[h.k])+h.j.b+h.e.a;if(k>j&&d>j){j=Ixb(c.n[h.k])+Ixb(c.d[h.k])+h.j.b+h.e.a}else{e=false;a.a&&(Fmb(),Emb);break}}if(!e){break}}a.a&&(Fmb(),Emb);return e}
function Jv(a){var b,c,d,e,f,g,h,i;if(isNaN(a)){return Rv(),Qv}if(a<-9223372036854775808){return Rv(),Pv}if(a>=9223372036854775807){return Rv(),Ov}e=false;if(a<0){e=true;a=-a}d=0;if(a>=dzb){d=hw(a/dzb);a-=d*dzb}c=0;if(a>=czb){c=hw(a/czb);a-=c*czb}b=hw(a);f=Ev(b,c,d);e&&(g=~f.l+1&azb,h=~f.m+(g==0?1:0)&azb,i=~f.h+(g==0&&h==0?1:0)&bzb,f.l=g,f.m=h,f.h=i,undefined);return f}
function JO(a){var b,c,d,e,f,g,h;e=DW(a);if(Qob(new Tob(e))){h=new VN(0,0,a.e.j.a,a.e.j.b);for(c=new Tob(e);c.a<c.c.c.length;){b=Wv(Rob(c),129);d=new VN(b.e.i.a,b.e.i.b,b.e.j.a,b.e.j.b);TN(h,d)}g=new FP((f=Wv(a.e,7).d,new EP(f.d,f.b,f.a,f.c)));g.d=-h.e;g.a=h.e+h.b-a.e.j.b;g.b=-h.d;g.c=h.d+h.c-a.e.j.a;Wv(a.e,7).d.b=g.b;Wv(a.e,7).d.d=g.d;Wv(a.e,7).d.c=g.c;Wv(a.e,7).d.a=g.a}}
function Y0(a){var b,c,d,e,f;for(f=new Tob(a.f);f.a<f.c.c.length;){e=Wv(Rob(f),7);for(d=new Tob(e.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);if(gw(rJ(c.d.f,(Mjb(),vjb)))!==gw((Xib(),Vib))){throw new $J((b=lX(a),nAb+(b==null?Dlb(a.k):b)+"' has its layer constraint set to LAST or LAST_SEPARATE, but has "+'at least one outgoing edge. Connections between nodes with these '+qAb))}}}}
function Rfb(a,b,c,d){var e,f,g,h,i,j;for(f=new Tob(a);f.a<f.c.c.length;){e=Wv(Rob(f),12);g=e.c;if(b.a.R(g)){h=(fgb(),dgb)}else if(c.a.R(g)){h=(fgb(),egb)}else{throw new slb('Source port must be in one of the port sets.')}i=e.d;if(b.a.R(i)){j=(fgb(),dgb)}else if(c.a.R(i)){j=(fgb(),egb)}else{throw new slb('Target port must be in one of the port sets.')}vU(d,new lgb(e,h,j))}}
function bQ(a,b){var c,d,e,f,g,h;if('edges' in b.a){h=Pu(b,'edges');if(!h.hc()){throw new GQ("The 'edges' property of a node has to be an array.",h,b)}f=h.hc();for(g=0;g<f.a.length;++g){e=gu(f,g);if(!e.kc()){throw new GQ("All elements of the 'edges' property must be objects.",e,b)}aQ(a,e.kc())}}if(Mzb in b.a){d=Pu(b,Mzb).hc();for(g=0;g<d.a.length;++g){c=gu(d,g).kc();bQ(a,c)}}}
function fS(a){var b,c,d,e,f,g,h,i;for(d=new Tob(a.a.a);d.a<d.c.c.length;){c=Wv(Rob(d),78);c.g=null;for(g=(i=(new Snb(c.a.a)).a.bb().mb(),new Ynb(i));g.a.G();){e=(b=Wv(g.a.H(),21),Wv(b.yb(),25));BI(e.g);(!c.g||e.j.d<c.g.j.d)&&(c.g=e)}for(f=(h=(new Snb(c.a.a)).a.bb().mb(),new Ynb(h));f.a.G();){e=(b=Wv(f.a.H(),21),Wv(b.yb(),25));e.g.a=e.j.d-c.g.j.d;e.g.b=e.j.e-c.g.j.e}}return a}
function Nab(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;c=false;n=$yb*a.b.f*a.b.d;for(e=new Tob(b.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);j=new Tob(d.a);f=Wv(Rob(j),9);k=Uab(a.a[f.k]);while(j.a<j.c.c.length){h=Wv(Rob(j),9);l=Uab(a.a[h.k]);if(k!=l){m=Xjb(a.b,f,h);g=f.i.b+f.j.b+f.e.a+k.a+m;i=h.i.b-h.e.d+l.a;if(g>i+n){o=k.i+l.i;l.a=(l.i*l.a+k.i*k.a)/o;l.i=o;k.g=l;c=true}}f=h;k=l}}return c}
function XY(a){var b,c,d,e,f,g;if(gw(rJ(a,(eM(),TL)))===gw((KM(),GM))||gw(rJ(a,TL))===gw(FM)){for(g=new Tob(a.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);if(f.g==(sN(),$M)||f.g==pN){return false}}}if(MM(Wv(rJ(a,TL),28))){for(e=nX(a,(sN(),ZM)).mb();e.G();){d=Wv(e.H(),7);if(d.b.c.length!=0){return false}}}for(c=Uh(mX(a));Cm(c);){b=Wv(Dm(c),12);if(b.c.f==b.d.f){return false}}return true}
function KW(a,b){var c,d,e,f,g,h,i,j,k;e=a.f;g=e.j.a;f=e.j.b;if(g<=0&&f<=0){return sN(),qN}j=a.i.a;k=a.i.b;h=a.j.a;c=a.j.b;switch(b.e){case 2:case 1:if(j<0){return sN(),rN}else if(j+h>g){return sN(),ZM}break;case 4:case 3:if(k<0){return sN(),$M}else if(k+c>f){return sN(),pN}}i=(j+h/2)/g;d=(k+c/2)/f;return i+d<=1&&i-d<=0?(sN(),rN):i+d>=1&&i-d>=0?(sN(),ZM):d<0.5?(sN(),$M):(sN(),pN)}
function pP(a,b,c,d,e,f,g){var h,i,j,k,l,m;m=new UN;for(j=b.mb();j.G();){h=Wv(j.H(),627);for(l=new Tob(sW(h));l.a<l.c.c.length;){k=Wv(Rob(l),129);if(gw(oW(k,(eM(),tL)))===gw((EK(),CK))){nP(m,k,false,d,e,f,g);TN(a,m)}}}for(i=c.mb();i.G();){h=Wv(i.H(),627);for(l=new Tob(sW(h));l.a<l.c.c.length;){k=Wv(Rob(l),129);if(gw(oW(k,(eM(),tL)))===gw((EK(),BK))){nP(m,k,true,d,e,f,g);TN(a,m)}}}}
function f8(a,b){var c,d,e,f,g,h,i,j;for(i=new Tob(b.f);i.a<i.c.c.length;){h=Wv(Rob(i),7);for(e=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[h.b,h.e]))))));Cm(e);){d=Wv(Dm(e),12);c=d.c==h?d.d:d.c;f=c.f;if(b==f){continue}j=Wv(rJ(d,(Rib(),Eib)),24).a;j<0&&(j=0);g=f.k;if(a.b[g]==0){if(d.d==c){a.a[g]-=j+1;a.a[g]<=0&&a.c[g]>0&&QI(a.e,f)}else{a.c[g]-=j+1;a.c[g]<=0&&a.a[g]>0&&QI(a.d,f)}}}}}
function tcb(a,b){var c,d,e,f,g,h,i,j,k;for(g=new Tob(b.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);for(j=new Tob(f.a);j.a<j.c.c.length;){i=Wv(Rob(j),9);k=new GU;h=0;for(e=Uh(iX(i));Cm(e);){c=Wv(Dm(e),12);Wv(rJ(c,(Rib(),Eib)),24).a>h&&(h=Wv(rJ(c,Eib),24).a)}for(d=Uh(iX(i));Cm(d);){c=Wv(Dm(d),12);i.d!=c.c.f.d&&Wv(rJ(c,(Rib(),Eib)),24).a==h&&vU(k,new RJ(c.c.f,c))}Gpb(k,a.c);uU(a.b,i.k,k)}}}
function ucb(a,b){var c,d,e,f,g,h,i,j,k;for(g=new Tob(b.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);for(j=new Tob(f.a);j.a<j.c.c.length;){i=Wv(Rob(j),9);k=new GU;h=0;for(e=Uh(mX(i));Cm(e);){c=Wv(Dm(e),12);Wv(rJ(c,(Rib(),Eib)),24).a>h&&(h=Wv(rJ(c,Eib),24).a)}for(d=Uh(mX(i));Cm(d);){c=Wv(Dm(d),12);i.d!=c.d.f.d&&Wv(rJ(c,(Rib(),Eib)),24).a==h&&vU(k,new RJ(c.d.f,c))}Gpb(k,a.c);uU(a.f,i.k,k)}}}
function g3(a){b3();var b,c,d,e,f,g,h,i,j,k;this.b=new i3;this.c=new GU;this.a=new GU;for(i=Seb(),j=0,k=i.length;j<k;++j){h=i[j];ssb(a3,h,new GU)}for(c=a.mb();c.G();){b=Wv(c.H(),75);xU(this.a,Zdb(b));b.g.a.Y()==0?Wv(qsb(a3,b.e),20).ib(b):vU(this.c,b)}for(f=(g=(new aob(a3)).a.bb().mb(),new fob(g));f.a.G();){e=(d=Wv(f.a.H(),21),Wv(d.zb(),20));Gpb(e,this.b)}Dpb(Wv(qsb(a3,(Ieb(),neb)),20))}
function E$(a,b){var c,d,e,f,g,h,i;i=Wv(rJ(b,(eM(),TL)),28);if(!(i==(KM(),GM)||i==FM)){return}f=(c=Wv(rJ(b,(Rib(),Xhb)),15).a,new HI(b.e.a+b.a.b+b.a.c+2*c,b.e.b+b.a.d+b.a.a+2*c)).b;for(h=new Tob(a.a);h.a<h.c.c.length;){g=Wv(Rob(h),9);if(g.g!=(CX(),xX)){continue}d=Wv(rJ(g,hib),32);if(d!=(sN(),ZM)&&d!=rN){continue}e=Ixb(Yv(rJ(g,Cib)));i==GM&&(e*=f);g.i.b=e-Wv(rJ(g,SL),10).b;fX(g,false,true)}}
function fZ(a,b){var c,d,e,f,g,h,i,j;c=new uX(a.d.c);sX(c,(CX(),wX));sJ(c,(eM(),TL),Wv(rJ(b,TL),28));sJ(c,JL,Wv(rJ(b,JL),86));c.k=a.d.b++;vU(a.b,c);c.j.b=b.j.b;c.j.a=0;j=(sN(),ZM);f=Ao(nX(b,j));for(i=new Tob(f);i.a<i.c.c.length;){h=Wv(Rob(i),7);PX(h,c)}g=new RX;QX(g,j);PX(g,b);g.i.a=c.j.a;g.i.b=c.j.b/2;e=new RX;QX(e,tN(j));PX(e,c);e.i.b=c.j.b/2;e.i.a=-e.j.a;d=new hW;dW(d,g);eW(d,e);return c}
function m3(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o;i=new Dh;Np(a,i);e=new deb(b);n=new GU;vU(n,(o=a.j,Wv(um(dq(!o?(a.j=new eq(a)):o)),7)));m=new GU;while(n.c.length!=0){h=Wv(Rob(new Tob(n)),7);m.c[m.c.length]=h;d=Sm(a,h);for(g=new Nqb(d.b.mb());g.b.G();){f=Wv(g.b.H(),12);if(beb(e,f,c)){l=Wv(Gd(i,f),20);for(k=l.mb();k.G();){j=Wv(k.H(),7);zU(m,j,0)!=-1||(n.c[n.c.length]=j,true)}}}BU(n,h)}return e}
function fmb(a,b){var c,d,e,f,g,h,i;c=RegExp(b,'g');h=xv($F,Txb,2,0,5,1);d=0;i=a;f=null;while(true){g=c.exec(i);if(g==null||i==''){h[d]=i;break}else{h[d]=gmb(i,0,g.index);i=gmb(i,g.index+g[0].length,(bmb(),i.length));c.lastIndex=0;if(f==i){h[d]=i.substr(0,1);i=imb(i,1,i.length-1)}f=i;++d}}if((bmb(),a.length)>0){e=h.length;while(e>0&&h[e-1]==''){--e}e<h.length&&(h.length=e,undefined)}return h}
function NO(a){var b,c,d,e,f,g;for(g=new Tob(AW(a.e));g.a<g.c.c.length;){f=Wv(Rob(g),161);switch(Wv(f.e,7).g.e){case 4:a.q.b=Nlb(a.q.b,(c=Wv(f.e,7).d,new EP(c.d,c.b,c.a,c.c)).c);break;case 2:a.q.c=Nlb(a.q.c,(d=Wv(f.e,7).d,new EP(d.d,d.b,d.a,d.c)).b);break;case 1:a.q.d=Nlb(a.q.d,(e=Wv(f.e,7).d,new EP(e.d,e.b,e.a,e.c)).a);break;case 3:a.q.a=Nlb(a.q.a,(b=Wv(f.e,7).d,new EP(b.d,b.b,b.a,b.c)).d);}}}
function Ns(a,b,c,d,e){var f,g,h;f=b.$b(c,a.b);if(f<0){g=a.e;if(!g){e[0]=0;return d>0?As(a,c,d):a}a.e=Ns(g,b,c,d,e);d==0&&e[0]!=0?--a.a:d>0&&e[0]==0&&++a.a;a.j=PH(a.j,d-e[0]);return Gs(a)}else if(f>0){h=a.g;if(!h){e[0]=0;return d>0?Bs(a,c,d):a}a.g=Ns(h,b,c,d,e);d==0&&e[0]!=0?--a.a:d>0&&e[0]==0&&++a.a;a.j=PH(a.j,d-e[0]);return Gs(a)}e[0]=a.c;if(d==0){return Fs(a)}a.j=PH(a.j,d-a.c);a.c=d;return a}
function Q7(a){var b,c,d,e,f,g,h;a.o=new Uvb;d=new aJ;for(g=new Tob(a.e.a);g.a<g.c.c.length;){f=Wv(Rob(g),61);m7(f).c.length==1&&(TI(d,f,d.c.b,d.c),true)}while(d.b!=0){f=Wv(d.b==0?null:(Bxb(d.b!=0),$I(d,d.a.a)),61);if(m7(f).c.length==0){continue}b=Wv(yU(m7(f),0),89);c=f.g.c.length>0;h=c7(b,f);c?p7(h.c,b):p7(h.g,b);m7(h).c.length==1&&(TI(d,h,d.c.b,d.c),true);e=new RJ(f,b);Tvb(a.o,e);BU(a.e.a,f)}}
function Hs(a,b,c,d,e){var f,g,h;f=b.$b(c,a.b);if(f<0){g=a.e;if(!g){e[0]=0;return a}a.e=Hs(g,b,c,d,e);if(e[0]>0){if(d>=e[0]){--a.a;a.j=XH(a.j,e[0])}else{a.j=XH(a.j,d)}}return e[0]==0?a:Gs(a)}else if(f>0){h=a.g;if(!h){e[0]=0;return a}a.g=Hs(h,b,c,d,e);if(e[0]>0){if(d>=e[0]){--a.a;a.j=XH(a.j,e[0])}else{a.j=XH(a.j,d)}}return Gs(a)}e[0]=a.c;if(d>=a.c){return Fs(a)}else{a.c-=d;a.j=XH(a.j,d);return a}}
function BQ(a,b,c){var d,e,f,g,h,i,j,k;for(i=new Tob(c.b);i.a<i.c.c.length;){h=Wv(Rob(i),9);g=Wv(rJ(h,(Rib(),sib)),55);if(g){k=BQ(a,b,g);h.j.a=(f=Wv(rJ(k,Xhb),15).a,new HI(k.e.a+k.a.b+k.a.c+2*f,k.e.b+k.a.d+k.a.a+2*f)).a;h.j.b=(e=Wv(rJ(k,Xhb),15).a,new HI(k.e.a+k.a.b+k.a.c+2*e,k.e.b+k.a.d+k.a.a+2*e)).b}}j=new sI;d=$v(rJ(c,(eM(),kL)));d!=null&&emb(d,'de.cau.cs.kieler.fixed')?JP(c,j):ZQ(b,c,j);return c}
function bR(a){var b,c,d,e,f,g,h,i;h=Wv(rJ(a,(eM(),aM)),18);i=Wv(rJ(a,bM),18);d=Wv(rJ(a,(Rib(),Xhb)),15).a;a.d.a+=d;a.d.b+=d;a.e.a+=2*d;a.e.b+=2*d;sJ(a,Xhb,new llb(0));e=(c=Wv(rJ(a,Xhb),15).a,new HI(a.e.a+a.a.b+a.a.c+2*c,a.e.b+a.a.d+a.a.a+2*c));b=new II(e);if(h.kb((DN(),zN))){g=Wv(rJ(a,IL),15).a;f=Wv(rJ(a,HL),15).a;if(i.kb((MN(),KN))){g<=0&&(g=20);f<=0&&(f=20)}b.a=Nlb(e.a,g);b.b=Nlb(e.b,f)}cR(a,e,b)}
function rV(a,b,c){var d,e,f,g,h,i,j,k;if(b.k==0){b.k=1;g=c;if(!c){e=new GU;f=(d=Wv(Hkb(Kz),11),new atb(d,Wv(exb(d,d.length),11),0));g=new RJ(e,f)}Wv(g.a,20).ib(b);b.g==(CX(),xX)&&Wv(g.b,18).ib(Wv(rJ(b,(Rib(),hib)),32));for(i=new Tob(b.f);i.a<i.c.c.length;){h=Wv(Rob(i),7);for(k=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[new fY(h),new lY(h)]))))));Cm(k);){j=Wv(Dm(k),7);rV(a,j.f,g)}}return g}return null}
function QW(a,b,c,d){var e,f,g,h,i;i=new II(b.i);i.a+=b.j.a/2;i.b+=b.j.b/2;h=Wv(rJ(b,(Rib(),tib)),15).a;f=a.e;g=a.a;e=a.d;switch(Wv(rJ(b,hib),32).e){case 1:i.a+=g.b+e.a-c/2;i.b=-d-h;b.i.b=-(g.d+h+e.b);break;case 2:i.a=f.a+g.b+g.c+h;i.b+=g.d+e.b-d/2;b.i.a=f.a+g.c+h-e.a;break;case 3:i.a+=g.b+e.a-c/2;i.b=f.b+g.d+g.a+h;b.i.b=f.b+g.a+h-e.b;break;case 4:i.a=-c-h;i.b+=g.d+e.b-d/2;b.i.a=-(g.b+h+e.a);}return i}
function $Q(a,b){var c,d,e,f,g,h,i;for(f=new Tob(b.b);f.a<f.c.c.length;){e=Wv(Rob(f),9);g=rJ(e,(Rib(),uib));if(aw(g,7)){h=Wv(g,7);i=QW(b,e,h.j.a,h.j.b);h.i.a=i.a;h.i.b=i.b;QX(h,Wv(rJ(e,hib),32))}}c=(d=Wv(rJ(b,(Rib(),Xhb)),15).a,new HI(b.e.a+b.a.b+b.a.c+2*d,b.e.b+b.a.d+b.a.a+2*d));if(Wv(rJ(b,jib),18).kb((ohb(),hhb))){sJ(a,(eM(),TL),(KM(),FM));Wv(rJ(hX(a),jib),18).ib(khb);WW(a,c,false)}else{WW(a,c,true)}}
function VW(a,b,c){var d,e,f,g,h;h=null;switch(b.e){case 1:for(e=new Tob(a.f);e.a<e.c.c.length;){d=Wv(Rob(e),7);if(Ckb(Ixb(Xv(rJ(d,(Rib(),kib)))))){return d}}h=new RX;sJ(h,(Rib(),kib),(xkb(),xkb(),wkb));break;case 2:for(g=new Tob(a.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);if(Ckb(Ixb(Xv(rJ(f,(Rib(),yib)))))){return f}}h=new RX;sJ(h,(Rib(),yib),(xkb(),xkb(),wkb));}if(h){PX(h,a);QX(h,c);LW(h.i,a.j,c)}return h}
function pk(a,b){var c,d,e,f,g,h,i;_b(b);Xb(a.a.t(b.a));d=a.b;f=a.e;g=a.d;if(a.b){if(b.b){c=a.a.$b(a.e,b.e);if(c<0||c==0&&b.d==(Gh(),Fh)){f=b.e;g=b.d}}}else{d=b.b;f=b.e;g=b.d}e=a.c;h=a.g;i=a.f;if(a.c){if(b.c){c=a.a.$b(a.g,b.g);if(c>0||c==0&&b.f==(Gh(),Fh)){h=b.g;i=b.f}}}else{e=b.c;h=b.g;i=b.f}if(d&&e){c=a.a.$b(f,h);if(c>0||c==0&&g==(Gh(),Fh)&&i==(Gh(),Fh)){f=h;g=(Gh(),Fh);i=Eh}}return new sk(a.a,d,f,g,e,h,i)}
function h0(a,b,c,d){var e,f,g,h,i,j,k;if(c.c.f==b.f){return}e=new uX(a);sX(e,(CX(),zX));sJ(e,(Rib(),uib),c);sJ(e,(eM(),TL),(KM(),FM));d.c[d.c.length]=e;g=new RX;PX(g,e);QX(g,(sN(),rN));h=new RX;PX(h,e);QX(h,ZM);eW(c,g);f=new hW;qJ(f,c);sJ(f,CL,null);dW(f,h);eW(f,b);j0(e,g,h);j=new Fnb(c.b,0);while(j.b<j.d.Y()){i=(Bxb(j.b<j.d.Y()),Wv(j.d.sb(j.c=j.b++),33));k=Wv(rJ(i,tL),107);if(k==(EK(),BK)){vnb(j);vU(f.b,i)}}}
function Pfb(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q;f=c+(b.n+1)*a.a;g=b.b;e=new HI(f,g);for(i=(k=(new Snb(b.c.a)).a.bb().mb(),new Ynb(k));i.a.G();){h=(j=Wv(i.a.H(),21),Wv(j.yb(),12));o=MX(h.d);l=MX(h.c);n=new HI(f,l.b);q=new HI(f,o.b);m=new HI(c-10,l.b);p=new HI(d,o.b);o.a>=d&&l.a>=d&&(m.a=d);o.a<=c&&l.a<=c&&(p.a=c-10);b.c.a.Y()==1?fJ(h.a,Bv(tv(qz,1),Fzb,10,0,[m,n,q,p])):fJ(h.a,Bv(tv(qz,1),Fzb,10,0,[m,n,e,q,p]))}}
function cW(a,b){var c,d,e,f,g,h;f=a.c;g=a.d;dW(a,null);eW(a,null);b&&Ckb(Ixb(Xv(rJ(g,(Rib(),kib)))))?dW(a,VW(g.f,(djb(),bjb),(sN(),ZM))):dW(a,g);b&&Ckb(Ixb(Xv(rJ(f,(Rib(),yib)))))?eW(a,VW(f.f,(djb(),ajb),(sN(),rN))):eW(a,f);for(d=new Tob(a.b);d.a<d.c.c.length;){c=Wv(Rob(d),33);e=Wv(rJ(c,(eM(),tL)),107);e==(EK(),CK)?sJ(c,tL,BK):e==BK&&sJ(c,tL,CK)}h=Ckb(Ixb(Xv(rJ(a,(Rib(),Iib)))));sJ(a,Iib,(xkb(),h?vkb:wkb));a.a=lJ(a.a)}
function efb(a){var b,c,d,e,f,g;Teb(this);for(c=a.Y()-1;c<3;c++){a.rb(0,Wv(a.sb(0),10))}if(a.Y()<4){throw new slb('At (least dimension + 1) control points are necessary!')}else{this.c=3;this.e=true;this.f=true;this.d=false;Ueb(this,a.Y()+this.c-1);g=new GU;f=this.g.mb();for(b=0;b<this.c-1;b++){vU(g,Yv(f.H()))}for(e=a.mb();e.G();){d=Wv(e.H(),10);vU(g,Yv(f.H()));this.b.ib(new sfb(d,g));Cxb(0,g.c.length);g.c.splice(0,1)}}}
function scb(a){var b,c,d,e,f,g,h,i,j,k,l;l=new rcb;l.d=0;for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);l.d+=f.a.c.length}d=0;e=0;l.a=xv(mw,Yyb,26,a.c.c.length,12,1);j=0;l.e=xv(mw,Yyb,26,l.d,12,1);for(c=new Tob(a.c);c.a<c.c.c.length;){b=Wv(Rob(c),16);b.k=d++;l.a[b.k]=e++;k=0;for(i=new Tob(b.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);h.k=j++;l.e[h.k]=k++}}l.c=new wcb(l);l.b=Do(l.d);tcb(l,a);l.f=Do(l.d);ucb(l,a);return l}
function Lab(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;h=xv(mw,Yyb,26,b.c.c.length,12,1);j=xv(pB,uyb,132,b.c.c.length,0,1);for(l=a.a,m=0,n=l.length;m<n;++m){k=l[m];p=0;for(g=new Tob(k.f);g.a<g.c.c.length;){e=Wv(Rob(g),9);i=e.g;d=rY(e.d);++h[d];o=a.b.a*a.b.d;h[d]>0&&!!j[d]&&(o=Wjb(a.b,j[d],i));p=Nlb(p,e.d.c.b+o)}for(f=new Tob(k.f);f.a<f.c.c.length;){e=Wv(Rob(f),9);e.i.b=p+e.e.d;c=e.d;c.c.b=p+e.e.d+e.j.b+e.e.a;j[zU(c.b.c,c,0)]=e.g}}}
function n$(a){var b,c,d,e,f,g,h,i,j,k;for(i=new Tob(a.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);if(h.g!=(CX(),xX)){continue}e=Wv(rJ(h,(Rib(),hib)),32);if(e==(sN(),ZM)||e==rN){for(d=Uh(gX(h));Cm(d);){c=Wv(Dm(d),12);b=c.a;if(b.b==0){continue}j=c.c;if(j.f==h){f=(Bxb(b.b!=0),Wv(b.a.a.c,10));f.b=MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b}k=c.d;if(k.f==h){g=(Bxb(b.b!=0),Wv(b.c.b.c,10));g.b=MI(Bv(tv(qz,1),Fzb,10,0,[k.f.i,k.i,k.a])).b}}}}}
function U9(a,b,c,d){var e,f,g,h,i,j;g=new _9(a,b,c);i=new Fnb(d,0);e=false;while(i.b<i.d.Y()){h=(Bxb(i.b<i.d.Y()),Wv(i.d.sb(i.c=i.b++),102));if(h==b||h==c){vnb(i)}else if(!e&&Ixb(W9(h.g,h.d[0]).a)>Ixb(W9(g.g,g.d[0]).a)){Bxb(i.b>0);i.a.sb(i.c=--i.b);Anb(i,g);e=true}else if(!!h.e&&h.e.Y()>0){f=(!h.e&&(h.e=new GU),h.e).nb(b);j=(!h.e&&(h.e=new GU),h.e).nb(c);if(f||j){(!h.e&&(h.e=new GU),h.e).ib(g);++g.c}}}e||(d.c[d.c.length]=g,true)}
function s2(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o;if(c.d.f==b.f){return}e=new uX(a);sX(e,(CX(),zX));sJ(e,(Rib(),uib),c);sJ(e,(eM(),TL),(KM(),FM));d.c[d.c.length]=e;g=new RX;PX(g,e);QX(g,(sN(),rN));h=new RX;PX(h,e);QX(h,ZM);i=c.d;eW(c,g);f=new hW;qJ(f,c);sJ(f,CL,null);dW(f,h);eW(f,i);j=Wv(yU(g.b,0),12).c;k=j.f;l=k.g;m=Wv(yU(h.e,0),12).d;n=m.f;o=n.g;l==zX?sJ(e,qib,Wv(rJ(k,qib),7)):sJ(e,qib,j);o==zX?sJ(e,rib,Wv(rJ(n,rib),7)):sJ(e,rib,m)}
function $6(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;if(h=a.b[b],i=a.b[c],(j=Wv(rJ(h,(Rib(),oib)),20),!!j&&j.Y()!=0&&j.kb(i))||(k=h.g!=(CX(),zX)&&i.g!=zX,l=Wv(rJ(h,nib),9),m=Wv(rJ(i,nib),9),n=!!l&&l!=h||!!m&&m!=i,o=l!=m,p=_6(h,(sN(),$M)),q=_6(i,pN),r=n&&o||p||q,k&&r)||h.g==(CX(),BX)&&i.g==AX||i.g==(CX(),BX)&&h.g==AX){return false}g=a.b[b];d=a.b[c];m6(a.c,g,d);G6(a.d,g,d);f=M5(a.a,g,d)+a.c.d+a.d.d;e=M5(a.a,d,g)+a.c.b+a.d.b;return f>e}
function v2(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;g=b;m=b.d;k=b.c.f;n=b.d.f;l=rY(k.d);o=rY(n.d);for(h=l;h<o;h++){e=new uX(a);sX(e,(CX(),zX));sJ(e,(Rib(),uib),g);sJ(e,(eM(),TL),(KM(),FM));i=Wv(yU(a.c,h+1),16);rX(e,i);p=Wv(rJ(g,dM),15).a;if(p<0){p=0;sJ(g,dM,new llb(p))}e.j.b=p;j=Math.floor(p/2);d=new RX;QX(d,(sN(),rN));PX(d,e);d.i.b=j;f=new RX;QX(f,ZM);PX(f,e);f.i.b=j;eW(g,d);c=new hW;qJ(c,g);sJ(c,CL,null);dW(c,f);eW(c,m);w2(e,g,c);g=c}}
function Qeb(a,b){Ieb();if(a==b){return Reb(a)}switch(a.e){case 1:switch(b.e){case 4:return neb;case 1:return meb;case 2:return jeb;case 3:return qeb;}case 2:switch(b.e){case 1:return jeb;case 2:return ieb;case 3:return peb;case 4:return keb;}case 3:switch(b.e){case 2:return peb;case 3:return oeb;case 4:return Heb;case 1:return qeb;}case 4:switch(b.e){case 3:return Heb;case 4:return Geb;case 1:return neb;case 2:return keb;}}return Feb}
function s$(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p;l=new Wub;e=null;for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);for(i=new Tob(f.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);if(h.g!=(CX(),xX)){continue}k=Wv(rJ(h,(Rib(),gib)),9);if(k){r$(k,l);m=new RX;PX(m,h);n=Wv(rJ(h,hib),32);QX(m,n);o=Wv(yU(k.f,0),7);p=new hW;dW(p,m);eW(p,o)}}e=f}for(c=(j=(new Snb(l.a)).a.bb().mb(),new Ynb(j));c.a.G();){b=(d=Wv(c.a.H(),21),Wv(d.yb(),9));rX(b,e)}return l}
function RV(a,b,c){var d,e,f,g,h,i,j,k,l;e=new GU;for(j=new Tob(b.b);j.a<j.c.c.length;){i=Wv(Rob(j),9);h=Wv(rJ(i,(Rib(),sib)),55);if(h){d=RV(a,h,i);xU(e,d);PV(a,h,i);if(Wv(rJ(h,jib),18).kb((ohb(),hhb))){for(l=new Tob(i.f);l.a<l.c.c.length;){k=Wv(Rob(l),7);if(Smb(a.b,k)==null){f=NW(k,(KM(),IM),k.g,-(k.b.c.length-k.e.c.length),k.j,Wv(rJ(h,(eM(),sL)),59),h);sJ(f,uib,k);Umb(a.b,k,f);vU(h.b,f)}}}}}g=new GU;OV(a,b,c,e,g);!!c&&QV(a,b,c,g);return g}
function Obb(a){var b,c,d,e,f,g,h,i,j,k,l,m;b=ecb(a);for(k=(h=(new Snb(b)).a.bb().mb(),new Ynb(h));k.a.G();){j=(e=Wv(k.a.H(),21),Wv(e.yb(),9));l=j.e.d;m=j.j.b+j.e.a;a.d[j.k]=0;c=j;while((f=a.a[c.k])!=j){d=gcb(c,f);a.c==(Gbb(),Ebb)?(i=d.d.i.b+d.d.a.b-d.c.i.b-d.c.a.b):(i=d.c.i.b+d.c.a.b-d.d.i.b-d.d.a.b);g=Ixb(a.d[c.k])+i;a.d[f.k]=g;l=Nlb(l,f.e.d-g);m=Nlb(m,g+f.j.b+f.e.a);c=f}c=j;do{a.d[c.k]=Ixb(a.d[c.k])+l;c=a.a[c.k]}while(c!=j);a.b[j.k]=l+m}}
function Gcb(a,b,c){var d,e,f,g,h,i,j,k;d=a.a.k==(Lbb(),Kbb)?Uzb:Vzb;h=Hcb(a,new Fcb(b,c));if(!h.a&&h.c){QI(a.d,h);return d}else if(h.a){e=h.a.c;i=h.a.d;if(c){j=a.a.c==(Gbb(),Fbb)?i:e;f=a.a.c==Fbb?e:i;g=a.a.f[f.f.k];k=Ixb(a.a.n[g.k])+Ixb(a.a.d[f.f.k])+f.i.b+f.a.b-Ixb(a.a.d[j.f.k])-j.i.b-j.a.b}else{j=a.a.c==(Gbb(),Ebb)?i:e;f=a.a.c==Ebb?e:i;k=Ixb(a.a.n[a.a.f[f.f.k].k])+Ixb(a.a.d[f.f.k])+f.i.b+f.a.b-Ixb(a.a.d[j.f.k])-j.i.b-j.a.b}return k}return d}
function FY(a){var b,c,d,e,f;sJ(a.g,(Rib(),Thb),Eo(a.g.c));for(b=1;b<a.c.c.length-1;++b){sJ(Wv(yU(a.c,b),9),(eM(),JL),(oM(),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,fM]))))}for(d=WI(Eo(a.g.c),0);d.b!=d.d.c;){c=Wv(_ub(d),33);e=Wv(rJ(a.g,(eM(),JL)),86);if(Xe(e,Vsb((oM(),kM),Bv(tv(Gz,1),uyb,41,0,[gM,mM]))));else if(Xe(e,Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[iM,mM])))){vU(a.e.c,c);BU(a.g.c,c);f=new MY(a,c);sJ(a.g,Uhb,f)}else{GY(a,c);vU(a.i,a.d);sJ(a.g,Uhb,EY(a.i))}}}
function OW(a,b,c,d){var e,f,g,h,i,j,k;f=PW(d);h=Ckb(Ixb(Xv(rJ(d,(Mjb(),xjb)))));if((h||Ckb(Ixb(Xv(rJ(a,(eM(),AL))))))&&!MM(Wv(rJ(a,(eM(),TL)),28))){e=vN(f);i=VW(a,c,c==(djb(),bjb)?e:tN(e))}else{i=new RX;PX(i,a);k=i.i;k.a=b.a-a.i.a;k.b=b.b-a.i.b;wI(k,a.j.a,a.j.b);QX(i,KW(i,f));g=Wv(rJ(d,(Rib(),jib)),18);j=i.g;switch(f.e){case 2:case 1:(j==(sN(),$M)||j==pN)&&g.ib((ohb(),lhb));break;case 4:case 3:(j==(sN(),ZM)||j==rN)&&g.ib((ohb(),lhb));}}return i}
function G2(a){var b,c,d,e,f,g,h,i;d=Nl(Ao(a.a));e=(b=Wv(Hkb(_E),11),new atb(b,Wv(exb(b,b.length),11),0));while(d.a.G()||d.b.mb().G()){c=Wv(nm(d),12);h=c.c.g;i=c.d.g;if(h==(sN(),qN)){if(i!=qN){g=Reb(i);sJ(c,(Rib(),Mib),g);QX(c.c,i);Wsb(e,g);d.a.I()}}else{if(i==qN){g=Reb(h);sJ(c,(Rib(),Mib),g);QX(c.d,h);Wsb(e,g);d.a.I()}else{g=Qeb(h,i);sJ(c,(Rib(),Mib),g);Wsb(e,g);d.a.I()}}}e.c==1?(f=Wv(itb(new jtb(e)),60)):(f=(Ieb(),Feb));aeb(a,f,false);return f}
function AI(b,c){var d,e,f,g;f=0;while(f<(bmb(),c.length)&&LI(c.charCodeAt(f),fzb)){++f}d=c.length;while(d>0&&LI(c.charCodeAt(d-1),gzb)){--d}if(f>=d){throw new slb('The given string does not contain any numbers.')}g=fmb(c.substr(f,d-f),',|;|\r|\n');if(g.length!=2){throw new slb('Exactly two numbers are expected, '+g.length+' were found.')}try{b.a=clb(hmb(g[0]));b.b=clb(hmb(g[1]))}catch(a){a=OH(a);if(aw(a,130)){e=a;throw new slb(hzb+e)}else throw NH(a)}}
function Qdb(a,b,c){var d,e,f,g,h,i,j,k,l;i=c+b.d.c.a;for(l=new Tob(b.f);l.a<l.c.c.length;){k=Wv(Rob(l),7);d=MI(Bv(tv(qz,1),Fzb,10,0,[k.f.i,k.i,k.a]));f=new HI(0,d.b);if(k.g==(sN(),ZM)){f.a=i}else if(k.g==rN){f.a=c}else{continue}if(d.a==f.a){continue}e=k.e.c.length+k.b.c.length>1;for(h=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[k.b,k.e]))))));Cm(h);){g=Wv(Dm(h),12);j=g.c==k?g.d:g.c;Jlb(MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b-f.b)>1&&Odb(a,g,f,e,k)}}}
function FR(a,b){var c,d,e,f,g,h;for(g=new rnb((new inb(a.f.b)).a);g.b;){f=pnb(g);e=Wv(f.yb(),251);if(b==1){if(e.yc()!=(sK(),rK)&&e.yc()!=nK){continue}}else{if(e.yc()!=(sK(),oK)&&e.yc()!=pK){continue}}d=Wv(Wv(f.zb(),27).b,25);h=Wv(Wv(f.zb(),27).a,78);c=h.c;switch(e.yc().e){case 2:d.j.d=a.e.a;d.j.c=Nlb(1,d.j.c+c);break;case 1:d.j.d=d.j.d+c;d.j.c=Nlb(1,d.j.c-c);break;case 4:d.j.e=a.e.b;d.j.b=Nlb(1,d.j.b+c);break;case 3:d.j.e=d.j.e+c;d.j.b=Nlb(1,d.j.b-c);}}}
function bdb(a,b,c,d,e){var f,g,h,i,j,k,l,m,n;m=(mp(),new ntb);h=new GU;adb(a,c,a.d.Mc(),h,m);adb(a,d,a.d.Nc(),h,m);i=new Fnb(h,0);while(i.b<i.d.Y()){f=(Bxb(i.b<i.d.Y()),Wv(i.d.sb(i.c=i.b++),80));j=new Fnb(h,i.b);while(j.b<j.d.Y()){g=(Bxb(j.b<j.d.Y()),Wv(j.d.sb(j.c=j.b++),80));gdb(f,g,a.a)}}ddb(h,Wv(rJ(b,(Rib(),Gib)),154));idb(h);n=-1;for(l=new Tob(h);l.a<l.c.c.length;){k=Wv(Rob(l),80);if(Jlb(k.k-k.a)<dAb){continue}n=Plb(n,k.i);a.d.Kc(k,e)}a.b.a.Q();return n+1}
function r3(a,b,c){var d,e;e=new II(b);d=new II(a.j);switch(c.e){case 1:case 8:case 7:uI(e,-d.a/2,-d.b);uI(b,0,-(0.5+d.b));break;case 3:case 4:case 5:uI(e,-d.a/2,0);uI(b,0,0.5+d.b);break;case 0:uI(e,-d.a/2,-d.b);uI(b,0,-(0.5+-d.b));break;case 10:case 2:uI(e,0,-d.b/2);uI(b,0,-(0.5+d.b));break;case 6:uI(e,-d.a,d.b/2);uI(b,0,-(0.5+d.b));break;case 9:uI(e,-d.a/2,0);uI(b,0,-(0.5+d.b));break;case 11:uI(e,-d.a,-d.b/2);uI(b,0,-(0.5+d.b));}vI(BI(a.i),e);return new Cfb(a)}
function Gmb(a,b,c,d,e){Fmb();var f,g,h,i,j,k,l;Exb(a,'src');Exb(c,'dest');k=tb(a);h=tb(c);Axb((k.g&4)!=0,'srcType is not an array');Axb((h.g&4)!=0,'destType is not an array');j=k.c;f=h.c;Axb((j.g&1)!=0?j==f:(f.g&1)==0,"Array types don't match");l=a.length;i=c.length;if(b<0||d<0||e<0||b+e>l||d+e>i){throw new nkb}if(((j.g&1)==0||(j.g&4)!=0)&&k!=h){if(a===c&&b<d){b+=e;for(g=d+e;g-->d;){c[g]=a[--b]}}else{for(g=d+e;d<g;){c[d++]=a[b++]}}}else e>0&&dxb(a,b,c,d,e,true)}
function cR(a,b,c){var d,e,f,g,h;d=Wv(rJ(a,(Mjb(),jjb)),18);c.a>b.a&&(d.kb((zgb(),tgb))?(a.d.a+=(c.a-b.a)/2):d.kb(vgb)&&(a.d.a+=c.a-b.a));c.b>b.b&&(d.kb((zgb(),xgb))?(a.d.b+=(c.b-b.b)/2):d.kb(wgb)&&(a.d.b+=c.b-b.b));if(Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))&&(c.a>b.a||c.b>b.b)){for(h=new Tob(a.b);h.a<h.c.c.length;){g=Wv(Rob(h),9);if(g.g==(CX(),xX)){e=Wv(rJ(g,hib),32);e==(sN(),ZM)?(g.i.a+=c.a-b.a):e==pN&&(g.i.b+=c.b-b.b)}}}f=a.a;a.e.a=c.a-f.b-f.c;a.e.b=c.b-f.d-f.a}
function Ms(a,b,c,d,e,f){var g,h,i;g=b.$b(c,a.b);if(g<0){h=a.e;if(!h){f[0]=0;if(d==0&&e>0){return As(a,c,e)}return a}a.e=Ms(h,b,c,d,e,f);if(f[0]==d){e==0&&f[0]!=0?--a.a:e>0&&f[0]==0&&++a.a;a.j=PH(a.j,e-f[0])}return Gs(a)}else if(g>0){i=a.g;if(!i){f[0]=0;if(d==0&&e>0){return Bs(a,c,e)}return a}a.g=Ms(i,b,c,d,e,f);if(f[0]==d){e==0&&f[0]!=0?--a.a:e>0&&f[0]==0&&++a.a;a.j=PH(a.j,e-f[0])}return Gs(a)}f[0]=a.c;if(d==a.c){if(e==0){return Fs(a)}a.j=PH(a.j,e-a.c);a.c=e}return a}
function gfb(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q;i=a.e;n=a.f;g=a.d;o=a.c;k=o-1;p=a.g;l=Eo(a.g.xb(1,a.g.Y()-1));j=new GU;for(c=0;c<a.b.Y()-1;c++){h=CI(EI(xI(Wv(a.b.sb(c+1),92).a),Wv(a.b.sb(c),92).a),o/(Ixb(Yv(p.sb(c+o)))-Ixb(Yv(p.sb(c)))));j.c[j.c.length]=h}q=new GU;f=WI(l,0);m=new GU;for(b=0;b<k-1;b++){vU(q,Yv(_ub(f)))}for(e=new Tob(j);e.a<e.c.c.length;){d=Wv(Rob(e),10);vU(q,Yv(_ub(f)));vU(m,new sfb(d,q));Cxb(0,q.c.length);q.c.splice(0,1)}return new ffb(i,n,g,k,l,m)}
function fP(a){this.q=new AP;this.p=new AP;this.o=xv(mw,Yyb,26,(sN(),Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN])).length,12,1);this.i=xv(mw,Yyb,26,Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]).length,12,1);this.j=xv(kw,hyb,26,Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]).length,12,1);this.n=xv(kw,hyb,26,Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]).length,12,1);this.g=xv(Hz,uyb,100,Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]).length,0,1);this.c=new vsb(Oz);this.e=a;$ob(this.o);$ob(this.i);Yob(this.n,0)}
function _Q(a,b){var c,d,e,f,g,h,i,j,k,l;g=b.i!=null&&!b.b;g||nI(b,'Component Layout',1);c=Wv(rJ(a,(Rib(),Fib)),20);f=1/c.Y();if(Ckb(Ixb(Xv(rJ(a,(eM(),rL)))))){l=0;for(k=c.mb();k.G();){j=Wv(k.H(),31);++l;Jkb(tb(j));j.sc(a,rI(b,f))}}else{for(k=c.mb();k.G();){j=Wv(k.H(),31);j.sc(a,rI(b,f))}}for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);xU(a.b,d.a);d.a.c=xv(UF,syb,1,0,4,1)}for(i=new Tob(a.b);i.a<i.c.c.length;){h=Wv(Rob(i),9);rX(h,null)}a.c.c=xv(UF,syb,1,0,4,1);g||pI(b)}
function S9(a,b){var c,d,e,f,g,h,i,j,k,l,m;for(g=new Tob(b);g.a<g.c.c.length;){e=Wv(Rob(g),102);e.e=null;e.c=0}h=null;for(f=new Tob(b);f.a<f.c.c.length;){e=Wv(Rob(f),102);k=e.d[0];for(m=Wv(rJ(k,(Rib(),oib)),20).mb();m.G();){l=Wv(m.H(),9);(!e.e&&(e.e=new GU),e.e).ib(a.b[l.d.k][l.k]);++a.b[l.d.k][l.k].c}if(k.g==(CX(),AX)){if(h){for(j=An(new Bn(a.c,h),0);j.c;){i=Wv(ko(j),9);for(d=An(new Bn(a.c,k),0);d.c;){c=Wv(ko(d),9);Y9(a.b[i.d.k][i.k]).ib(a.b[c.d.k][c.k]);++a.b[c.d.k][c.k].c}}}h=k}}}
function gQ(a,b,c,d){var e,f,g,h,i,j;SP(b);f=Wv(rJ(d,(Rib(),jib)),18);h=(eM(),KL).b;if(h in b.a&&Pu(b,h).ic().a){return}i=new RX;sJ(i,uib,b);PX(i,c);g=Wv(Pu(b,'id'),97);Vmb(a.k,g.a,i);Umb(a.n,i,b);_P(b,i);hQ(b,i);dQ(a,b,i,d);QX(i,Wv(rJ(i,WL),32));j=Wv(rJ(c,TL),28);j==(KM(),JM)&&(j=IM);e=Wv(rJ(d,sL),59);e==(sK(),qK)&&(e=pK);RW(i,j,e,Wv(rJ(i,SL),10));switch(e.e){case 2:case 1:(i.g==(sN(),$M)||i.g==pN)&&f.ib((ohb(),lhb));break;case 4:case 3:(i.g==(sN(),ZM)||i.g==rN)&&f.ib((ohb(),lhb));}}
function Q5(a,b){var c,d,e,f,g,h,i,j;a.f=b;e=b.c.c.length;a.a=xv(qB,Txb,51,e,0,2);a.d=xv(qB,Txb,51,e,0,2);a.g=xv(qB,Txb,51,e,0,2);g=new Fnb(b.c,0);while(g.b<g.d.Y()){d=(Bxb(g.b<g.d.Y()),Wv(g.d.sb(g.c=g.b++),16));h=d.a.c.length;f=g.b-1;a.a[f]=xv(qB,Nzb,9,h,0,1);a.d[f]=xv(qB,Nzb,9,h,0,1);a.g[f]=xv(qB,Nzb,9,h,0,1);j=new Fnb(d.a,0);c=0;while(j.b<j.d.Y()){i=(Bxb(j.b<j.d.Y()),Wv(j.d.sb(j.c=j.b++),9));i.k=c++;a.d[f][j.b-1]=i;a.a[f][j.b-1]=i;a.g[f][j.b-1]=i}}a.b=new _4(a.d);a.e.c&&(a.b.e=true)}
function gZ(a){var b,c,d,e,f,g;e=new GU;for(g=new Tob(a.c.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);f.g==(sN(),ZM)&&(e.c[e.c.length]=f,true)}if(a.d.a==(sK(),pK)&&!MM(Wv(rJ(a.c,(eM(),TL)),28))){for(d=Uh(mX(a.c));Cm(d);){c=Wv(Dm(d),12);vU(e,c.c)}}sJ(a.c,(Rib(),Whb),new llb(a.c.j.a));sJ(a.c,Vhb,(xkb(),xkb(),wkb));vU(a.b,a.c);b=null;a.e==1?(b=jZ(a,a.c,rY(a.c.d),a.c.j.a)):a.e==0?(b=iZ(a,a.c,rY(a.c.d),a.c.j.a)):a.e==3?(b=kZ(a,a.c,a.c.j.a)):a.e==2&&(b=hZ(a,a.c,a.c.j.a));!!b&&new HY(a.c,a.b,Ixb(Yv(b.b)))}
function Mab(a,b,c){var d,e,f,g,h,i,j,k;e=b.g;Ckb(Ixb(Xv(rJ(b,(Rib(),Vhb)))))&&(e=(CX(),wX));if(b.k>=0){return false}else if(!!c.e&&e==(CX(),wX)&&e!=c.e){return false}else{b.k=c.b;vU(c.f,b)}c.e=e;if(e==(CX(),zX)||e==BX||e==wX){for(g=new Tob(b.f);g.a<g.c.c.length;){f=Wv(Rob(g),7);for(k=(d=new Tob((new lY(f)).a.e),new nY(d));Qob(k.a);){j=Wv(Rob(k.a),12).d;h=j.f;i=h.g;if(b.d!=h.d){if(e==wX){if(i==wX){if(Mab(a,h,c)){return true}}}else{if(i==zX||i==BX){if(Mab(a,h,c)){return true}}}}}}}return true}
function K3(a,b){var c,d,e,f,g,h,i,j,k;fJ(a.a,Bv(tv(qz,1),Fzb,10,0,[b.a,b.b]));Ue(a.c,b.e);a.q.d=a.q.d|b.d;a.q.a=a.q.a|b.c;h=Qlb(a.j.e,b.k);i=Nlb(a.j.e+a.j.b,b.n);SN(a.j,b.j,h,0,i-h);stb(a.d,b.f);b.f.c.f==b.f.d.f&&wS(a.n,true,true,true,true);g=new vtb;j=new vtb;for(e=(k=(new Snb(a.d.a)).a.bb().mb(),new Ynb(k));e.a.G();){d=(f=Wv(e.a.H(),21),Wv(f.yb(),12));stb(g,d.c);stb(j,d.d)}c=g.a.Y()-j.a.Y();if(c<0){vS(a.n,true,(sK(),oK));vS(a.n,false,pK)}else if(c>0){vS(a.n,false,(sK(),oK));vS(a.n,true,pK)}}
function tP(b,c){var d,e,f,g,h,i,j,k,l,m;h=0;while(h<(bmb(),c.length)&&yP(c.charCodeAt(h),fzb)){++h}d=c.length;while(d>0&&yP(c.charCodeAt(d-1),gzb)){--d}if(h<d){l=fmb(c.substr(h,d-h),',|;');try{for(j=0,k=l.length;j<k;++j){i=l[j];g=fmb(i,'=');if(g.length!=2){throw new slb('Expecting a list of key-value pairs.')}f=hmb(g[0]);m=clb(hmb(g[1]));emb(f,'top')?(b.d=m):emb(f,'left')?(b.b=m):emb(f,Azb)?(b.a=m):emb(f,'right')&&(b.c=m)}}catch(a){a=OH(a);if(aw(a,130)){e=a;throw new slb(hzb+e)}else throw NH(a)}}}
function Ubb(a,b){var c,d,e,f,g,h,i,j,k;k=new aJ;for(h=(j=(new aob(a.c)).a.bb().mb(),new fob(j));h.a.G();){f=(e=Wv(h.a.H(),21),Wv(e.zb(),200));f.b==0&&(TI(k,f,k.c.b,k.c),true)}while(k.b!=0){f=Wv(k.b==0?null:(Bxb(k.b!=0),$I(k,k.a.a)),200);for(d=new Tob(f.d);d.a<d.c.c.length;){c=Wv(Rob(d),279);b.k==(Lbb(),Jbb)?(c.b.a=Qlb(c.b.a,f.a+c.a)):(c.b.a=Nlb(c.b.a,f.a+c.a));--c.b.b;c.b.b==0&&QI(k,c.b)}}for(g=(i=(new aob(a.c)).a.bb().mb(),new fob(i));g.a.G();){f=(e=Wv(g.a.H(),21),Wv(e.zb(),200));b.g[f.c.k]=f.a}}
function yZ(a,b,c){var d,e,f,g;f=a.i;e=MI(Bv(tv(qz,1),Fzb,10,0,[b.i,b.f.i]));d=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a]));g=b.d;switch(b.g.e){case 4:f.a=Qlb(e.a,d.a)-g.b-a.j.a-c;f.b=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).b+c;break;case 2:f.a=Nlb(e.a+b.j.a,d.a)+g.c+c;f.b=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).b+c;break;case 1:f.a=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).a+c;f.b=Qlb(e.b,d.b)-g.d-a.j.b-c;break;case 3:f.a=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).a+c;f.b=Nlb(e.b+b.j.b,d.b)+g.a+c;}}
function zZ(a,b,c){var d,e,f,g;f=a.i;e=MI(Bv(tv(qz,1),Fzb,10,0,[b.i,b.f.i]));d=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a]));g=b.d;switch(b.g.e){case 4:f.a=Qlb(e.a,d.a)-g.b-a.j.a-c;f.b=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).b-a.j.b-c;break;case 2:f.a=Nlb(e.a+b.j.a,d.a)+g.c+c;f.b=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).b-a.j.b-c;break;case 1:f.a=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).a+c;f.b=Qlb(e.b,d.b)-g.d-a.j.b-c;break;case 3:f.a=MI(Bv(tv(qz,1),Fzb,10,0,[b.f.i,b.i,b.a])).a+c;f.b=Nlb(e.b+b.j.b,d.b)+g.a+c;}}
function MQ(a){var b,c;c=Wv(rJ(a,(Rib(),jib)),18);b=XQ(HQ);Ckb(Ixb(Xv(rJ(a,(Mjb(),rjb)))))?RQ(b,(d0(),W_)):TQ(b,(d0(),W_));rJ(a,(bK(),aK))!=null&&QQ(b,IQ);switch(Wv(rJ(a,(eM(),sL)),59).e){case 2:PQ(RQ(b,(d0(),L_)),K_);break;case 3:PQ(RQ(b,(d0(),o_)),n_);break;case 4:PQ(RQ(b,(d0(),c0)),b0);}c.kb((ohb(),fhb))&&PQ(RQ(b,(d0(),m_)),l_);gw(rJ(a,Bjb))!==gw((I1(),G1))&&TQ(b,(d0(),P_));gw(rJ(a,Fjb))!==gw((g4(),e4))&&gw(rJ(a,eib))===gw((NK(),JK))&&PQ(b,(d0(),w_));if(c.kb(mhb)){RQ(b,(d0(),T_));TQ(b,S_)}return b}
function zhb(){zhb=iI;shb=new Ahb('ONE_SIDED',0,true,false,false);whb=new Ahb('TWO_SIDED',1,false,false,false);thb=new Ahb('ONE_SIDED_BEST_OF_UP_OR_DOWN',2,true,true,false);xhb=new Ahb('TWO_SIDED_BEST_OF_UP_OR_DOWN',3,false,true,false);uhb=new Ahb('ONE_SIDED_BEST_OF_UP_OR_DOWN_ORTHOGONAL_HYPEREDGES',4,true,true,true);yhb=new Ahb('TWO_SIDED_BEST_OF_UP_OR_DOWN_ORTHOGONAL_HYPEREDGES',5,false,true,true);vhb=new Ahb('ONE_SIDED_ORTHOGONAL_HYPEREDGES',6,true,false,true);rhb=new Ahb('OFF',7,false,false,false)}
function LV(a,b,c,d,e,f,g){var h,i,j,k,l,m,n;l=Ckb(Ixb(Xv(rJ(b,(Mjb(),yjb)))));m=null;f==(djb(),ajb)&&d.c.f==c?(m=d.c):f==bjb&&d.d.f==c&&(m=d.d);j=g;if(!g||!l||!!m){k=(sN(),qN);m?(k=m.g):MM(Wv(rJ(c,(eM(),TL)),28))&&(k=f==ajb?rN:ZM);i=JV(a,b,c,f,k,d);h=IV((hX(c),d));if(f==ajb){dW(h,Wv(yU(i.f,0),7));eW(h,e)}else{dW(h,e);eW(h,Wv(yU(i.f,0),7))}j=new UV(d,h,i,Wv(rJ(i,(Rib(),uib)),7),f,!m)}else{vU(g.e,d);n=Olb(Wv(rJ(g.d,(eM(),dM)),15).a,Wv(rJ(d,dM),15).a);sJ(g.d,dM,new llb(n))}Fd(a.a,d,new XV(j.d,b,f));return j}
function T1(a,b,c,d){var e,f,g,h,i,j,k,l;f=new uX(a);sX(f,(CX(),BX));sJ(f,(eM(),TL),(KM(),FM));e=0;if(b){g=new RX;sJ(g,(Rib(),uib),b);sJ(f,uib,b.f);QX(g,(sN(),rN));PX(g,f);l=Wv(FU(b.b,xv(dB,gAb,12,b.b.c.length,0,1)),47);for(j=0,k=l.length;j<k;++j){i=l[j];eW(i,g)}sJ(b,Bib,f);++e}if(c){h=new RX;sJ(f,(Rib(),uib),c.f);sJ(h,uib,c);QX(h,(sN(),ZM));PX(h,f);l=Wv(FU(c.e,xv(dB,gAb,12,c.e.c.length,0,1)),47);for(j=0,k=l.length;j<k;++j){i=l[j];dW(i,h)}sJ(c,Bib,f);++e}sJ(f,(Rib(),aib),Elb(e));d.c[d.c.length]=f;return f}
function MV(a,b){var c,d,e,f,g,h,i;for(g=ud(a.a).mb();g.G();){f=Wv(g.H(),12);if(f.b.c.length>0){d=new IU(Wv(Dd(a.a,f),18));Gpb(d,new $V(b));e=new Fnb(f.b,0);while(e.b<e.d.Y()){c=(Bxb(e.b<e.d.Y()),Wv(e.d.sb(e.c=e.b++),33));h=-1;switch(Wv(rJ(c,(eM(),tL)),107).e){case 2:h=d.c.length-1;break;case 1:h=d.c.length/2|0;break;case 3:h=0;}if(h!=-1){i=(Cxb(h,d.c.length),Wv(d.c[h],114));vU(i.b.b,c);Wv(rJ(hX(i.b.c.f),(Rib(),jib)),18).ib((ohb(),ghb));Wv(rJ(hX(i.b.c.f),jib),18).ib(ehb);vnb(e);sJ(c,xib,f)}}}dW(f,null);eW(f,null)}}
function H7(a){var b,c,d,e,f,g,h,i,j,k,l;k=a.e.a.c.length;for(g=new Tob(a.e.a);g.a<g.c.c.length;){f=Wv(Rob(g),61);f.j=false}a.i=xv(mw,Yyb,26,k,12,1);a.g=xv(mw,Yyb,26,k,12,1);a.n=new GU;e=0;l=new GU;for(i=new Tob(a.e.a);i.a<i.c.c.length;){h=Wv(Rob(i),61);h.b=e++;h.c.c.length==0&&vU(a.n,h);xU(l,h.g)}b=0;for(d=new Tob(l);d.a<d.c.c.length;){c=Wv(Rob(d),89);c.b=b++;c.e=false}j=l.c.length;if(a.b==null||a.b.length<j){a.b=xv(kw,hyb,26,j,12,1);a.c=xv(KH,xAb,26,j,13,1)}else{dpb(a.c)}a.d=l;a.p=new Xub(op(a.d.c.length));a.j=1}
function z0(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;p=a.d;q=b.d;n=Wv(oX(a,(djb(),ajb)).mb().H(),7);t=Wv(oX(a,bjb).mb().H(),7);o=Wv(oX(b,ajb).mb().H(),7);u=Wv(oX(b,bjb).mb().H(),7);l=Wv(FU(n.b,xv(dB,gAb,12,1,0,1)),47);r=Wv(FU(t.e,xv(dB,gAb,12,1,0,1)),47);m=Wv(FU(o.b,xv(dB,gAb,12,1,0,1)),47);s=Wv(FU(u.e,xv(dB,gAb,12,1,0,1)),47);rX(a,q);for(e=0,i=m.length;e<i;++e){c=m[e];eW(c,n)}for(f=0,j=s.length;f<j;++f){c=s[f];dW(c,t)}rX(b,p);for(g=0,k=l.length;g<k;++g){c=l[g];eW(c,o)}for(d=0,h=r.length;d<h;++d){c=r[d];dW(c,u)}}
function gR(a){var b,c,d,e,f,g,h,i;for(f=new Tob(a.a.b);f.a<f.c.c.length;){e=Wv(Rob(f),25);e.vc()}i=new HI(Uzb,Uzb);b=new HI(Vzb,Vzb);for(d=new Tob(a.a.b);d.a<d.c.c.length;){c=Wv(Rob(d),25);i.a=Qlb(i.a,c.j.d);i.b=Qlb(i.b,c.j.e);b.a=Nlb(b.a,c.j.d+c.j.c);b.b=Nlb(b.b,c.j.e+c.j.b)}for(h=Jd(a.c).mb();h.G();){g=Wv(h.H(),27);c=Wv(g.b,25);i.a=Qlb(i.a,c.j.d);i.b=Qlb(i.b,c.j.e);b.a=Nlb(b.a,c.j.d+c.j.c);b.b=Nlb(b.b,c.j.e+c.j.b)}a.d=zI(new HI(i.a,i.b));a.e=EI(new HI(b.a,b.b),i);a.a.a.c=xv(UF,syb,1,0,4,1);a.a.b.c=xv(UF,syb,1,0,4,1)}
function P$(a){var b,c,d,e,f,g,h;h=Wv(yU(a.f,0),7);if(h.e.c.length!=0&&h.b.c.length!=0){throw new ulb('Interactive layout does not support NORTH/SOUTH ports with incoming _and_ outgoing edges.')}if(h.e.c.length!=0){f=Uzb;for(c=new Tob(h.e);c.a<c.c.c.length;){b=Wv(Rob(c),12);g=b.d.f;d=Wv(rJ(g,(eM(),GL)),65);f=Qlb(f,g.i.a-d.b)}return new $c(_b(f))}if(h.b.c.length!=0){e=Vzb;for(c=new Tob(h.b);c.a<c.c.c.length;){b=Wv(Rob(c),12);g=b.c.f;d=Wv(rJ(g,(eM(),GL)),65);e=Nlb(e,g.i.a+g.j.a+d.c)}return new $c(_b(e))}return zb(),zb(),yb}
function JV(a,b,c,d,e,f){var g,h,i,j,k,l,m;j=d==(djb(),ajb)?f.c:f.d;i=PW(b);if(j.f==c){g=Wv(Smb(a.b,j),9);if(!g){g=NW(j,Wv(rJ(c,(eM(),TL)),28),e,d==ajb?-1:1,j.j,i,b);sJ(g,(Rib(),uib),j);Umb(a.b,j,g)}}else{k=Wv(rJ(f,(eM(),dM)),15).a;g=NW((l=new tJ,m=Wv(rJ(b,(Rib(),Jib)),15).a*Wv(rJ(b,(Mjb(),qjb)),15).a/2,sJ(l,tib,new llb(m)),l),Wv(rJ(c,TL),28),e,d==ajb?-1:1,new HI(k,k),i,b);h=KV(a,g,c,d);sJ(g,uib,h);Umb(a.b,h,g)}Wv(rJ(b,(Rib(),jib)),18).ib((ohb(),hhb));MM(Wv(rJ(b,(eM(),TL)),28))?sJ(b,TL,(KM(),HM)):sJ(b,TL,(KM(),IM));return g}
function Iab(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A;d=Wv(rJ(b,(Mjb(),wjb)),15).a;v=Wv(rJ(b,Kjb),24).a;m=4;e=3;w=20/v;n=false;i=0;g=$xb;do{f=i!=1;l=i!=0;A=0;for(q=a.a,s=0,u=q.length;s<u;++s){o=q[s];o.g=null;Jab(a,o,f,l,d);A+=Jlb(o.a)}do{h=Nab(a,b)}while(h);for(p=a.a,r=0,t=p.length;r<t;++r){o=p[r];c=Uab(o).a;if(c!=0){for(k=new Tob(o.f);k.a<k.c.c.length;){j=Wv(Rob(k),9);j.i.b+=c}}}if(i==0||i==1){--m;if(m<=0&&(A<g||-m>v)){i=2;g=$xb}else if(i==0){i=1;g=A}else{i=0;g=A}}else{n=A>=g||g-A<w;g=A;n&&--e}}while(!(n&&e<=0))}
function vZ(a,b,c){var d,e,f,g,h,i,j,k,l,m,n;l=Wv(FU(a.f,xv(BB,mAb,7,a.f.c.length,0,1)),346);for(j=0,k=l.length;j<k;++j){i=l[j];if(c!=(djb(),ajb)){h=Wv(FU(i.e,xv(dB,gAb,12,i.e.c.length,0,1)),47);for(e=0,f=h.length;e<f;++e){d=h[e];n=Wv(rJ(d.d.f,(Mjb(),vjb)),85);!Ckb(Ixb(Xv(rJ(d,(Rib(),Iib)))))&&!(b==(Xib(),Uib)&&n==Vib)&&cW(d,true)}}if(c!=bjb){g=Wv(FU(i.b,xv(dB,gAb,12,i.b.c.length,0,1)),47);for(e=0,f=g.length;e<f;++e){d=g[e];m=Wv(rJ(d.c.f,(Mjb(),vjb)),85);!Ckb(Ixb(Xv(rJ(d,(Rib(),Iib)))))&&!(b==(Xib(),Sib)&&m==Tib)&&cW(d,true)}}}}
function RW(a,b,c,d){var e,f,g,h,i;g=a.g;if(g==(sN(),qN)&&b!=(KM(),IM)&&b!=(KM(),JM)){g=KW(a,c);QX(a,g);rJ(a,(eM(),LL))==null&&g!=qN&&(a.i.a!=0||a.i.b!=0)&&sJ(a,LL,new llb(JW(a,g)))}if(b==(KM(),GM)){i=0;switch(g.e){case 1:case 3:f=a.f.j.a;f>0&&(i=a.i.a/f);break;case 2:case 4:e=a.f.j.b;e>0&&(i=a.i.b/e);}sJ(a,(Rib(),Cib),i)}h=a.j;if(d){a.a.a=d.a;a.a.b=d.b}else if(b!=IM&&b!=JM&&g!=qN){switch(g.e){case 1:a.a.a=h.a/2;break;case 2:a.a.a=h.a;a.a.b=h.b/2;break;case 3:a.a.a=h.a/2;a.a.b=h.b;break;case 4:a.a.b=h.b/2;}}else{a.a.a=h.a/2;a.a.b=h.b/2}}
function zJ(a){var b,c,d,e;if(aw(a.a,10)){return xI(Wv(a.a,10))}else if(aw(a.a,66)){return Xsb(Wv(a.a,86))}else if(aw(a.a,50)){return Wv(a.a,50).Wc()}else if(aw(a.a,191)){b=new Vwb;e=(d=new rwb((new wwb((new Gob(Wv(a.a,191).a)).a)).b),new Mob(d));while(Bnb(e.a.a)){Rwb(b,(c=pwb(e.a),c.yb()))}return b}else if(aw(a.a,13)){return new IU(Wv(a.a,13))}else if(aw(a.a,44)){b=new jJ;e=WI(Wv(a.a,44),0);while(e.b!=e.d.c){QI(b,Wv(_ub(e),10))}return b}else if(aw(a.a,58)){b=new aJ;e=WI(Wv(a.a,58),0);while(e.b!=e.d.c){QI(b,_ub(e))}return b}else{return a.a}}
function o1(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;h=0;o=0;i=Xob(a.f,a.f.length);f=a.d;g=a.i;d=a.a;e=a.b;do{n=0;for(k=new Tob(a.p);k.a<k.c.c.length;){j=Wv(Rob(k),9);m=n1(a,j);c=true;(a.q==(I1(),B1)||a.q==E1)&&(c=Ckb(Ixb(Xv(m.b))));if(Wv(m.a,24).a<0&&c){++n;i=Xob(a.f,a.f.length);a.d=a.d+Wv(m.a,24).a;o+=f-a.d;f=a.d+Wv(m.a,24).a;g=a.i;d=Ao(a.a);e=Ao(a.b)}else{a.f=Xob(i,i.length);a.d=f;a.a=(_b(d),d?new IU((Oh(),d)):Bo(new Tob(null)));a.b=(_b(e),e?new IU((Oh(),e)):Bo(new Tob(null)));a.i=g}}++h;l=n!=0&&Ckb(Ixb(Xv(b.B(new RJ(Elb(o),Elb(h))))))}while(l)}
function yO(a,b,c,d){var e,f,g,h,i,j,k;if(!Qob(new Tob(zW(a)))){return d}k=wO(Wv(oW(a,(eM(),JL)),86));for(i=new Tob(zW(a));i.a<i.c.c.length;){h=Wv(Rob(i),129);j=wO(Wv(oW(h,JL),86));j==(uO(),tO)&&(j=k);qW(h,j.e);e=zO(c,j);e.c=Nlb(e.c,h.e.j.a);e.b+=h.e.j.b+b}for(g=new Lsb((new Fsb(c)).a);htb(g.a);){f=(g.b=itb(g.a),new Psb(g.c,g.b));e=Wv(f.b.b[f.a.e],62);e.b-=b;switch(Wv(f.a,67).e){case 12:case 13:case 14:d.d=Nlb(d.d,e.b+b);break;case 15:d.b=Nlb(d.b,e.c+b);break;case 17:d.c=Nlb(d.c,e.c+b);break;case 18:case 19:case 20:d.a=Nlb(d.a,e.b+b);}}return d}
function mgb(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p;igb(this);c==(fgb(),dgb)?stb(this.g,a):stb(this.o,a);n=rAb;m=4.9E-324;for(j=(g=(new Snb(b.a)).a.bb().mb(),new Ynb(g));j.a.G();){h=(e=Wv(j.a.H(),21),Wv(e.yb(),27));k=Wv(h.a,223);d=Wv(h.b,12);l=d.c;l==a&&(l=d.d);k==dgb?stb(this.g,l):stb(this.o,l);p=MI(Bv(tv(qz,1),Fzb,10,0,[l.f.i,l.i,l.a])).b;n=n<p?n:p;m=m>p?m:p}o=MI(Bv(tv(qz,1),Fzb,10,0,[a.f.i,a.i,a.a])).b;kgb(this,o,n,m);for(i=(f=(new Snb(b.a)).a.bb().mb(),new Ynb(f));i.a.G();){h=(e=Wv(i.a.H(),21),Wv(e.yb(),27));stb(this.c,Wv(h.b,12))}this.f=false}
function cQ(a,b,c,d){var e,f,g,h,i,j;h=(eM(),KL).b;if(h in b.a&&Pu(b,h).ic().a){return}j=Pu(b,Dzb);if(!j){throw new GQ("Labels must have a property 'text'.",null,b)}else if(!j.lc()){throw new GQ("A label's 'text' property must be a string.",j,b)}i=j.lc().a;f=new dX(i);sJ(f,(Rib(),uib),b);Umb(a.f,f,b);_P(b,f);hQ(b,f);aw(c,9)?vU(Wv(c,9).c,f):aw(c,12)?vU(Wv(c,12).b,f):aw(c,7)&&vU(Wv(c,7).c,f);if(aw(c,12)){g=Wv(rJ(f,tL),107);_P(b,f);sJ(f,tL,g);e=Wv(rJ(d,jib),18);switch(g.e){case 2:case 3:e.ib((ohb(),ghb));case 1:case 0:e.ib((ohb(),ehb));sJ(f,tL,(EK(),AK));}}}
function UW(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;f=0;g=0;for(j=new Tob(a.a);j.a<j.c.c.length;){h=Wv(Rob(j),9);f=Nlb(f,h.e.b);g=Nlb(g,h.e.c)}for(i=new Tob(a.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);c=Wv(rJ(h,(eM(),lL)),103);switch(c.e){case 1:o=0;break;case 2:o=1;break;case 5:o=0.5;break;default:d=0;l=0;for(n=new Tob(h.f);n.a<n.c.c.length;){m=Wv(Rob(n),7);m.b.c.length==0||++d;m.e.c.length==0||++l}d+l==0?(o=0.5):(o=l/(d+l));}q=a.c;k=h.j.a;r=(q.a-k)*o;o>0.5?(r-=g*2*(o-0.5)):o<0.5&&(r+=f*2*(0.5-o));e=h.e.b;r<e&&(r=e);p=h.e.c;r>q.a-p-k&&(r=q.a-p-k);h.i.a=b+r}}
function Kv(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G;c=a.l&8191;d=a.l>>13|(a.m&15)<<9;e=a.m>>4&8191;f=a.m>>17|(a.h&255)<<5;g=(a.h&1048320)>>8;h=b.l&8191;i=b.l>>13|(b.m&15)<<9;j=b.m>>4&8191;k=b.m>>17|(b.h&255)<<5;l=(b.h&1048320)>>8;B=c*h;C=d*h;D=e*h;F=f*h;G=g*h;if(i!=0){C+=c*i;D+=d*i;F+=e*i;G+=f*i}if(j!=0){D+=c*j;F+=d*j;G+=e*j}if(k!=0){F+=c*k;G+=d*k}l!=0&&(G+=c*l);n=B&azb;o=(C&511)<<13;m=n+o;q=B>>22;r=C>>9;s=(D&262143)<<4;t=(F&31)<<17;p=q+r+s+t;v=D>>18;w=F>>5;A=(G&4095)<<8;u=v+w+A;p+=m>>22;m&=azb;u+=p>>22;p&=azb;u&=bzb;return Ev(m,p,u)}
function jZ(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w;q=a.d.c.c.c.length;if(c>=q-1){return null}e=new GU;e.c[e.c.length]=b;u=b;g=c;o=-1;h=Wv(yU(a.d.c.c,c),16);for(n=0;n<h.a.c.length;++n){r=Wv(yU(h.a,n),9);if(r==b){o=n;break}}p=eZ(a,1,o,c,q,a.a);if(!p){return null}v=a.a;m=0;f=0;while(!!u&&v>1&&g<q-1){k=fZ(a,u);l=Wv(yU(a.d.c.c,g+1),16);w=Wv(p.sb(m++),24).a;s=Slb(w,l.a.c.length);qX(k,s,l);!!u&&(e.c[e.c.length]=u,true);u=k;--v;++f;++g}t=(d-(e.c.length-1)*a.d.d)/e.c.length;for(j=new Tob(e);j.a<j.c.c.length;){i=Wv(Rob(j),9);i.j.a=t}return new RJ(Elb(f),t)}
function iZ(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w;if(c<=0){return null}e=new GU;e.c[e.c.length]=b;u=b;g=c;o=-1;h=Wv(yU(a.d.c.c,c),16);for(n=0;n<h.a.c.length;++n){q=Wv(yU(h.a,n),9);if(q==b){o=n;break}}p=eZ(a,0,o,c,a.d.c.c.c.length,a.a);if(!p){return null}v=a.a;m=0;f=0;t=o;while(!!u&&v>1&&g>1){k=fZ(a,u);h=Wv(yU(a.d.c.c,g),16);l=Wv(yU(a.d.c.c,g-1),16);w=Wv(p.sb(m++),24).a;r=Slb(w,l.a.c.length);qX(u,r,l);qX(k,t,h);t=r;!!u&&(e.c[e.c.length]=u,true);u=k;--v;++f;--g}s=(d-(e.c.length-1)*a.d.d)/e.c.length;for(j=new Tob(e);j.a<j.c.c.length;){i=Wv(Rob(j),9);i.j.a=s}return new RJ(Elb(f),s)}
function sV(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;a.b=a.c;o=Xv(rJ(b,(eM(),_L)));n=o==null||Ckb((Dxb(o),o));f=Wv(rJ(b,(Rib(),jib)),18).kb((ohb(),hhb));e=Wv(rJ(b,TL),28);c=!(e==(KM(),EM)||e==GM||e==FM);if(n&&(c||!f)){for(l=new Tob(b.b);l.a<l.c.c.length;){j=Wv(Rob(l),9);j.k=0}m=new GU;for(k=new Tob(b.b);k.a<k.c.c.length;){j=Wv(Rob(k),9);d=rV(a,j,null);if(d){i=new kW;qJ(i,b);sJ(i,fib,Wv(d.b,18));YW(i.a,b.a);for(h=Wv(d.a,20).mb();h.G();){g=Wv(h.H(),9);vU(i.b,g);g.a=i}m.ib(i)}}f&&(a.b=a.a)}else{m=new opb(Bv(tv(mB,1),{38:1,39:1,42:1,3:1,8:1,5:1,6:1},55,0,[b]))}return m}
function T4(a){var b,c,d,e,f,g,h,i,j;for(c=new Tob(a.a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);for(g=b.i.mb();g.G();){f=Wv(g.H(),25);if(b.f==f.f){continue}tK(a.a.d)?(i=a.a.g.tc(b,f)):(i=a.a.g.uc(b,f));d=b.g.a+b.j.c+i-f.g.a;d=Math.ceil(d);d=0>d?0:d;if(!!b.o&&!!f.o&&aw(b,82)&&aw(f,82)&&!sr(or(Wv(b,82).d,Wv(f,82).d))){e=x7(new A7,a.d);h=hw(Llb(f.g.a-b.g.a));f7(i7(h7(j7(g7(new k7,0>h?0:h),1),e),a.c[b.f.d]));f7(i7(h7(j7(g7(new k7,0>-h?0:-h),1),e),a.c[f.f.d]))}else{j=1;(aw(b,82)&&aw(f,93)||aw(f,82)&&aw(b,93))&&(j=2);f7(i7(h7(j7(g7(new k7,hw(d)),j),a.c[b.f.d]),a.c[f.f.d]))}}}}
function tQ(){tQ=iI;sQ=new vtb;rQ=uQ(Bv(tv(rz,1),syb,79,0,[(eM(),kL),xL]));oQ=uQ(Bv(tv(rz,1),syb,79,0,[ML,UL,(Mjb(),Hjb),yL,(Rib(),Eib),Kjb,Cjb]));kQ=uQ(Bv(tv(rz,1),syb,79,0,[mL,qL,KL,wL,BL,EL,FL,$L,_L,AL,gjb,mjb,njb,xjb,rjb,yjb,Ijb,Djb,ijb]));nQ=uQ(Bv(tv(rz,1),syb,79,0,[IL,HL,DL,dM,LL,Dib,Xhb,Rhb,Jib,Ejb,qjb,wjb]));mQ=uQ(Bv(tv(rz,1),syb,79,0,[WL,lL,sL,uL,tL,vL,zL,NL,OL,PL,QL,RL,TL,VL,hjb,ljb,zjb,ojb,kjb,Ajb,Bjb,sjb,tjb,vjb,Fjb,Gjb,Jjb,Ljb,ujb]));lQ=uQ(Bv(tv(rz,1),syb,79,0,[JL,aM,bM,jjb]));qQ=uQ(Bv(tv(rz,1),syb,79,0,[jL,oL,CL,GL,SL,YL]));pQ=uQ(Bv(tv(rz,1),syb,79,0,[(RP(),OP)]))}
function AR(a){var b,c,d,e,f,g,h;b=0;for(f=new Tob(a.b.a);f.a<f.c.c.length;){d=Wv(Rob(f),78);d.b=0;d.c=0}zR(a,0);yR(a,a.g);fS(a.c);jS(a.c);c=(sK(),oK);hS(bS(gS(hS(bS(gS(hS(gS(a.c,c)),vK(c)))),c)));gS(a.c,oK);DR(a,a.g);ER(a,0);FR(a,0);GR(a,1);zR(a,1);yR(a,a.d);fS(a.c);for(g=new Tob(a.b.a);g.a<g.c.c.length;){d=Wv(Rob(g),78);b+=Jlb(d.c)}for(h=new Tob(a.b.a);h.a<h.c.c.length;){d=Wv(Rob(h),78);d.b=0;d.c=0}c=rK;hS(bS(gS(hS(bS(gS(hS(jS(gS(a.c,c))),vK(c)))),c)));gS(a.c,oK);DR(a,a.d);ER(a,1);FR(a,1);GR(a,0);jS(a.c);for(e=new Tob(a.b.a);e.a<e.c.c.length;){d=Wv(Rob(e),78);b+=Jlb(d.c)}return b}
function BR(a){var b,c,d,e,f,g,h;b=new GU;a.g=new GU;a.d=new GU;for(g=new rnb((new inb(a.f.b)).a);g.b;){f=pnb(g);vU(b,Wv(Wv(f.zb(),27).b,25));tK(Wv(f.yb(),251).yc())?vU(a.d,Wv(f.zb(),27)):vU(a.g,Wv(f.zb(),27))}yR(a,a.d);yR(a,a.g);a.c=new rS(a.b);pS(a.c,(fR(),eR));DR(a,a.d);DR(a,a.g);xU(b,a.c.a.b);a.e=new HI(Uzb,Uzb);a.a=new HI(Vzb,Vzb);for(d=new Tob(b);d.a<d.c.c.length;){c=Wv(Rob(d),25);a.e.a=Qlb(a.e.a,c.j.d);a.e.b=Qlb(a.e.b,c.j.e);a.a.a=Nlb(a.a.a,c.j.d+c.j.c);a.a.b=Nlb(a.a.b,c.j.e+c.j.b)}oS(a.c,new IR);h=0;do{e=AR(a);++h}while((h<2||e>$yb)&&h<10);oS(a.c,new KR);AR(a);iS(a.c);gR(a.f)}
function tT(a){oT();var b,c,d,e,f,g,h;h=new qT;for(c=new Tob(a);c.a<c.c.c.length;){b=Wv(Rob(c),48);(!h.b||b.c>=h.b.c)&&(h.b=b);if(!h.c||b.c<=h.c.c){h.d=h.c;h.c=b}(!h.e||b.d>=h.e.d)&&(h.e=b);(!h.f||b.d<=h.f.d)&&(h.f=b)}d=new xT((cT(),$S));RT(a,mT,new opb(Bv(tv(JA,1),syb,160,0,[d])));g=new xT(bT);RT(a,lT,new opb(Bv(tv(JA,1),syb,160,0,[g])));e=new xT(_S);RT(a,kT,new opb(Bv(tv(JA,1),syb,160,0,[e])));f=new xT(aT);RT(a,jT,new opb(Bv(tv(JA,1),syb,160,0,[f])));rT(d.c,$S);rT(e.c,_S);rT(f.c,aT);rT(g.c,bT);h.a.c=xv(UF,syb,1,0,4,1);xU(h.a,d.c);xU(h.a,Fo(e.c));xU(h.a,f.c);xU(h.a,Fo(g.c));return h}
function $O(a){var b,c,d,e,f,g,h,i,j,k;e=Wv(vW(a,(eM(),DL)),15).a;for(h=new Tob(uW(a));h.a<h.c.c.length;){g=Wv(Rob(h),626);c=new fP(g);c.d=e;c.k=Wv(oW(g,XL),15).a;d=Wv(oW(g,VL),149);b=Ckb(Ixb(Xv(rJ(Wv(g.e,9),(Rib(),$hb)))));for(k=new Tob(AW(g));k.a<k.c.c.length;){j=Wv(Rob(k),161);d==(UM(),SM)?XO(j,b,e):d==TM&&YO(j,e);JO(j)}LO(c,Wv(oW(g,aM),86).kb((DN(),CN)));NO(c);yO(c.e,c.d,c.c,c.p);_O(c);ZO(c);VO(c);i=new CP((f=Wv(g.e,9).b,new BP(f.d,f.b,f.a,f.c)));i.b=c.p.b+c.q.b;i.c=c.p.c+c.q.c;i.d=c.p.d+c.q.d;i.a=c.p.a+c.q.a;Wv(g.e,9).b.b=i.b;Wv(g.e,9).b.d=i.d;Wv(g.e,9).b.c=i.c;Wv(g.e,9).b.a=i.a}}
function c1(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;i=Wv(nX(a,(sN(),rN)).mb().H(),7).b;n=Wv(nX(a,ZM).mb().H(),7).e;h=i.c.length;t=MX(Wv(yU(a.f,0),7));while(h-->0){p=(Cxb(0,i.c.length),Wv(i.c[0],12));e=(Cxb(0,n.c.length),Wv(n.c[0],12));s=e.d.b;f=zU(s,e,0);fW(p,e.d,f);dW(e,null);eW(e,null);o=p.a;b&&QI(o,new II(t));for(d=WI(e.a,0);d.b!=d.d.c;){c=Wv(_ub(d),10);QI(o,new II(c))}r=p.b;for(m=new Tob(e.b);m.a<m.c.c.length;){l=Wv(Rob(m),33);r.c[r.c.length]=l}q=Wv(rJ(p,(eM(),CL)),44);g=Wv(rJ(e,CL),44);if(g){if(!q){q=new jJ;sJ(p,CL,q)}for(k=WI(g,0);k.b!=k.d.c;){j=Wv(_ub(k),10);QI(q,new II(j))}}}}
function XO(a,b,c){var d,e,f,g,h;f=Li(DW(a));if(f.Nb().V()){return}h=0;switch(Wv(a.e,7).g.e){case 4:case 2:h=b&&Ckb(Ixb(Xv(rJ(Wv(a.e,7),(Rib(),lib)))))?a.e.j.b:(a.e.j.b-Wv(f.Nb().sb(0),129).pc().b)/2-c;break;case 1:h=a.e.j.b;break;case 3:h=0;}Wv(a.e,7).g==(sN(),pN)&&Ii(f);for(e=new Tob(DW(a));e.a<e.c.c.length;){d=Wv(Rob(e),129);g=new II(a.e.i);switch(Wv(a.e,7).g.e){case 4:g.a=a.e.j.a+c;g.b=h+c;h+=c+d.e.j.b;break;case 2:g.a=-d.e.j.a-c;g.b=h+c;h+=c+d.e.j.b;break;case 1:g.a=(a.e.j.a-d.e.j.a)/2;g.b=h+c;h+=c+d.e.j.b;break;case 3:g.a=(a.e.j.a-d.e.j.a)/2;g.b=h-c-d.e.j.b;h-=c+d.e.j.b;}d.e.i.a=g.a;d.e.i.b=g.b}}
function jR(a,b){var c,d,e,f,g,h,i,j,k,l;a.a=new NR(Tsb(Bz));for(d=new Tob(b.a);d.a<d.c.c.length;){c=Wv(Rob(d),347);h=new QR(Bv(tv(kA,1),syb,25,0,[]));vU(a.a.a,h);for(j=new Tob(c.d);j.a<j.c.c.length;){i=Wv(Rob(j),62);k=new pR(a,i);iR(k,Wv(rJ(c.c,(Rib(),fib)),18));if(!Qmb(a.g,c)){Umb(a.g,c,new HI(i.d,i.e));Umb(a.f,c,k)}vU(a.a.b,k);OR(h,k)}for(g=new Tob(c.b);g.a<g.c.c.length;){f=Wv(Rob(g),251);k=new pR(a,f.Bc());Umb(a.b,f,new RJ(h,k));iR(k,Wv(rJ(c.c,(Rib(),fib)),18));if(f.zc()){l=new qR(a,f.zc(),1);iR(l,Wv(rJ(c.c,fib),18));e=new QR(Bv(tv(kA,1),syb,25,0,[]));OR(e,l);Fd(a.c,f.yc(),new RJ(h,l))}}}return a.a}
function ccb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;p=b.c.c.length;if(p<3){return}n=xv(mw,Yyb,26,p,12,1);l=0;for(k=new Tob(b.c);k.a<k.c.c.length;){j=Wv(Rob(k),16);n[l++]=j.a.c.length}m=new Fnb(b.c,2);for(d=1;d<p-1;d++){c=(Bxb(m.b<m.d.Y()),Wv(m.d.sb(m.c=m.b++),16));o=new Tob(c.a);f=0;h=0;for(i=0;i<n[d+1];i++){t=Wv(Rob(o),9);if(i==n[d+1]-1||bcb(a,t,d+1,d)){g=n[d]-1;bcb(a,t,d+1,d)&&(g=a.d.e[Wv(Wv(Wv(yU(a.d.b,t.k),20).sb(0),27).a,9).k]);while(h<=i){s=Wv(yU(c.a,h),9);if(!bcb(a,s,d+1,d)){for(r=Wv(yU(a.d.b,s.k),20).mb();r.G();){q=Wv(r.H(),27);e=a.d.e[Wv(q.a,9).k];(e<f||e>g)&&stb(a.c,Wv(q.b,12))}}++h}f=g}}}}
function _9(a,b,c){var d,e,f,g,h,i;this.g=a;h=b.d.length;i=c.d.length;this.d=xv(qB,Nzb,9,h+i,0,1);for(g=0;g<h;g++){this.d[g]=b.d[g]}for(f=0;f<i;f++){this.d[h+f]=c.d[f]}if(b.e){this.e=Eo(b.e);this.e.nb(c);if(c.e){for(e=c.e.mb();e.G();){d=Wv(e.H(),102);if(d==b){continue}else this.e.kb(d)?--d.c:this.e.ib(d)}}}else if(c.e){this.e=Eo(c.e);this.e.nb(b)}this.f=b.f+c.f;this.a=b.a+c.a;this.a>0?Z9(this,this.f/this.a):W9(b.g,b.d[0]).a!=null&&W9(c.g,c.d[0]).a!=null?Z9(this,(Ixb(W9(b.g,b.d[0]).a)+Ixb(W9(c.g,c.d[0]).a))/2):W9(b.g,b.d[0]).a!=null?Z9(this,W9(b.g,b.d[0]).a):W9(c.g,c.d[0]).a!=null&&Z9(this,W9(c.g,c.d[0]).a)}
function x9(a,b){var c,d,e,f,g,h,i,j,k,l,m;switch(a.g.e){case 1:d=Wv(rJ(a,(Rib(),uib)),12);c=Wv(rJ(d,vib),44);!c?(c=new jJ):Ckb(Ixb(Xv(rJ(d,Iib))))&&(c=lJ(c));j=Wv(rJ(a,qib),7);k=MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a]));if(b<=k.a){return k.b}TI(c,k,c.a,c.a.a);l=Wv(rJ(a,rib),7);m=MI(Bv(tv(qz,1),Fzb,10,0,[l.f.i,l.i,l.a]));if(m.a<=b){return m.b}TI(c,m,c.c.b,c.c);i=WI(c,0);g=Wv(_ub(i),10);h=Wv(_ub(i),10);while(h.a<b&&i.b!=i.d.c){g=h;h=Wv(_ub(i),10)}return g.b+(b-g.a)/(h.a-g.a)*(h.b-g.b);case 3:f=Wv(rJ(Wv(yU(a.f,0),7),(Rib(),uib)),7);e=f.f;switch(f.g.e){case 1:return e.i.b;case 3:return e.i.b+e.j.b;}}return kX(a).b}
function KP(a){var b,c,d,e,f,g,h,i,j,k,l,m;k=gw(rJ(a.c.f,(Rib(),sib)))===gw(rJ(a.d.f,sib));g=new FI;c=Wv(rJ(a,(eM(),oL)),44);if(!!c&&c.b>=2){_I(a.a);d=0;for(m=WI(c,0);m.b!=m.d.c;){l=Wv(_ub(m),10);if(d==0){b=EI(EI(new HI(l.a,l.b),a.c.i),a.c.f.i);a.c.a.a=b.a;a.c.a.b=b.b}else if(d==c.b-1){b=EI(EI(new HI(l.a,l.b),a.d.i),a.d.f.i);a.d.a.a=b.a;a.d.a.b=b.b}else{QI(a.a,l)}++d}}if(k){for(i=WI(a.a,0);i.b!=i.d.c;){h=Wv(_ub(i),10);g.a=Nlb(g.a,h.a);g.b=Nlb(g.b,h.b)}}for(f=new Tob(a.b);f.a<f.c.c.length;){e=Wv(Rob(f),33);j=Wv(rJ(e,YL),10);if(j){e.i.a=j.a;e.i.b=j.b}if(k){g.a=Nlb(g.a,e.i.a+e.j.a);g.b=Nlb(g.b,e.i.b+e.j.b)}}return g}
function eQ(a,b,c){var d,e,f,g,h,i,j;SP(b);d=Wv(rJ(c,(Rib(),jib)),18);g=new uX(c);sJ(g,uib,b);vU(c.b,g);f=Wv(Pu(b,'id'),97);Vmb(a.i,f.a,g);Umb(a.j,g,b);_P(b,g);hQ(b,g);if('ports' in b.a){j=Pu(b,'ports');if(!j.hc()){throw new GQ("The 'ports' property of the node must be an array.",j,b)}i=j.hc();for(e=0;e<i.a.length;++e){aw(gu(i,e),69)&&gQ(a,Wv(gu(i,e),69),g,c)}}dQ(a,b,g,c);Mzb in b.a&&Pu(b,Mzb).hc().a.length>0&&sJ(g,$hb,(xkb(),xkb(),wkb));h=Wv(rJ(g,(eM(),TL)),28);h==(KM(),JM)?IM:h!=IM&&d.ib((ohb(),khb));Ckb(Ixb(Xv(rJ(g,qL))))&&d.ib((ohb(),fhb));if(Ckb(Ixb(Xv(rJ(g,AL))))){d.ib((ohb(),jhb));d.ib(ihb);sJ(g,TL,IM)}return g}
function iR(a,b){b.V()&&wS(a.n,true,true,true,true);b.t((sN(),eN))&&wS(a.n,true,true,true,false);b.t(_M)&&wS(a.n,false,true,true,true);b.t(mN)&&wS(a.n,true,true,false,true);b.t(oN)&&wS(a.n,true,false,true,true);b.t(fN)&&wS(a.n,false,true,true,false);b.t(aN)&&wS(a.n,false,true,false,true);b.t(nN)&&wS(a.n,true,false,false,true);b.t(lN)&&wS(a.n,true,false,true,false);b.t(jN)&&wS(a.n,true,true,true,true);b.t(cN)&&wS(a.n,true,true,true,true);b.t(jN)&&wS(a.n,true,true,true,true);b.t(bN)&&wS(a.n,true,true,true,true);b.t(kN)&&wS(a.n,true,true,true,true);b.t(iN)&&wS(a.n,true,true,true,true);b.t(hN)&&wS(a.n,true,true,true,true)}
function n1(a,b){var c,d,e,f,g,h,i,j,k,l;i=true;e=0;j=a.f[b.k];k=b.j.b+a.n;c=a.c[b.k][2];DU(a.a,j,Elb(Wv(yU(a.a,j),24).a-1+c));DU(a.b,j,Ixb(Yv(yU(a.b,j)))-k+c*a.e);++j;if(j>=a.i){++a.i;vU(a.a,Elb(1));vU(a.b,k)}else{d=a.c[b.k][1];DU(a.a,j,Elb(Wv(yU(a.a,j),24).a+1-d));DU(a.b,j,Ixb(Yv(yU(a.b,j)))+k-d*a.e)}(a.q==(I1(),B1)&&(Wv(yU(a.a,j),24).a>a.j||Wv(yU(a.a,j-1),24).a>a.j)||a.q==E1&&(Ixb(Yv(yU(a.b,j)))>a.k||Ixb(Yv(yU(a.b,j-1)))>a.k))&&(i=false);for(g=Uh(iX(b));Cm(g);){f=Wv(Dm(g),12);h=f.c.f;if(a.f[h.k]==j){l=n1(a,h);e=e+Wv(l.a,24).a;i=i&&Ckb(Ixb(Xv(l.b)))}}a.f[b.k]=j;e=e+a.c[b.k][0];return new RJ(Elb(e),(xkb(),i?wkb:vkb))}
function WW(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;m=new II(a.j);r=b.a/m.a;h=b.b/m.b;p=b.a-m.a;f=b.b-m.b;if(c){e=gw(rJ(a,(eM(),TL)))===gw((KM(),FM));for(o=new Tob(a.f);o.a<o.c.c.length;){n=Wv(Rob(o),7);switch(n.g.e){case 1:e||(n.i.a*=r);break;case 2:n.i.a+=p;e||(n.i.b*=h);break;case 3:e||(n.i.a*=r);n.i.b+=f;break;case 4:e||(n.i.b*=h);}}}for(j=new Tob(a.c);j.a<j.c.c.length;){i=Wv(Rob(j),33);k=i.i.a+i.j.a/2;l=i.i.b+i.j.b/2;q=k/m.a;g=l/m.b;if(q+g>=1){if(q-g>0&&l>=0){i.i.a+=p;i.i.b+=f*g}else if(q-g<0&&k>=0){i.i.a+=p*q;i.i.b+=f}}}a.j.a=b.a;a.j.b=b.b;sJ(a,(eM(),aM),(DN(),d=Wv(Hkb(Lz),11),new atb(d,Wv(exb(d,d.length),11),0)))}
function C7(a){var b,c,d,e,f,g,h,i,j,k;d=new GU;for(g=new Tob(a.e.a);g.a<g.c.c.length;){e=Wv(Rob(g),61);k=0;e.k.c=xv(UF,syb,1,0,4,1);for(c=new Tob(m7(e));c.a<c.c.c.length;){b=Wv(Rob(c),89);if(b.e){vU(e.k,b);++k}}k==1&&(d.c[d.c.length]=e,true)}for(f=new Tob(d);f.a<f.c.c.length;){e=Wv(Rob(f),61);while(e.k.c.length==1){j=Wv(Rob(new Tob(e.k)),89);a.b[j.b]=j.f;h=j.c;i=j.d;for(c=new Tob(m7(e));c.a<c.c.c.length;){b=Wv(Rob(c),89);b==j||(b.e?h==b.c||i==b.d?(a.b[j.b]-=a.b[b.b]-b.f):(a.b[j.b]+=a.b[b.b]-b.f):e==h?b.c==e?(a.b[j.b]+=b.f):(a.b[j.b]-=b.f):b.c==e?(a.b[j.b]-=b.f):(a.b[j.b]+=b.f))}BU(h.k,j);BU(i.k,j);h==e?(e=j.d):(e=j.c)}}}
function _fb(a){var b,c,d,e,f,g,h,i,j,k;j=new aJ;h=new aJ;for(f=new Tob(a);f.a<f.c.c.length;){d=Wv(Rob(f),77);d.e=d.d.c.length;d.k=d.j.c.length;d.e==0&&(TI(j,d,j.c.b,j.c),true);d.k==0&&d.g.a.Y()==0&&(TI(h,d,h.c.b,h.c),true)}g=-1;while(j.b!=0){d=Wv(un(j,0),77);for(c=new Tob(d.j);c.a<c.c.c.length;){b=Wv(Rob(c),117);k=b.b;k.n=Plb(k.n,d.n+1);g=Plb(g,k.n);--k.e;k.e==0&&(TI(j,k,j.c.b,j.c),true)}}if(g>-1){for(e=WI(h,0);e.b!=e.d.c;){d=Wv(_ub(e),77);d.n=g}while(h.b!=0){d=Wv(un(h,0),77);for(c=new Tob(d.d);c.a<c.c.c.length;){b=Wv(Rob(c),117);i=b.a;if(i.g.a.Y()!=0){continue}i.n=Slb(i.n,d.n-1);--i.k;i.k==0&&(TI(h,i,h.c.b,h.c),true)}}}}
function QV(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;i=new GU;for(f=new Tob(b.b);f.a<f.c.c.length;){e=Wv(Rob(f),9);for(h=new Tob(e.f);h.a<h.c.c.length;){g=Wv(Rob(h),7);k=null;for(t=Wv(FU(g.e,xv(dB,gAb,12,0,0,1)),47),u=0,v=t.length;u<v;++u){s=t[u];if(!SW(s.d.f,c)){r=LV(a,b,c,s,s.c,(djb(),bjb),k);r!=k&&(i.c[i.c.length]=r,true);r.c&&(k=r)}}j=null;for(o=Wv(FU(g.b,xv(dB,gAb,12,0,0,1)),47),p=0,q=o.length;p<q;++p){n=o[p];if(!SW(n.c.f,c)){r=LV(a,b,c,n,n.d,(djb(),ajb),j);r!=j&&(i.c[i.c.length]=r,true);r.c&&(j=r)}}}}for(m=new Tob(i);m.a<m.c.c.length;){l=Wv(Rob(m),187);zU(b.b,l.a,0)!=-1||vU(b.b,l.a);l.c&&(d.c[d.c.length]=l,true)}}
function WO(a){var b,c,d,e,f,g,h,i,j;d=a.e.e.j;b=Wv(oW(a.e,(eM(),aM)),86).kb((DN(),CN));PO(a);for(f=new Tob(AW(a.e));f.a<f.c.c.length;){e=Wv(Rob(f),161);h=Wv(oW(e,LL),15);!h&&(h=new llb(0));i=e.e.j;g=(c=Wv(e.e,7).d,new EP(c.d,c.b,c.a,c.c));j=new II(e.e.i);switch(Wv(e.e,7).g.e){case 4:j.a=-i.a-h.a;j.b=a.s-i.b-(b?g.a:0);a.s-=cP(a,(sN(),rN))+i.b+(b?g.d+g.a:0);break;case 2:j.a=d.a+h.a;j.b=a.a+(b?g.d:0);a.a+=cP(a,(sN(),ZM))+i.b+(b?g.d+g.a:0);break;case 1:j.a=a.f+(b?g.b:0);j.b=-e.e.j.b-h.a;a.f+=cP(a,(sN(),$M))+i.a+(b?g.b+g.c:0);break;case 3:j.a=a.r-i.a-(b?g.c:0);j.b=d.b+h.a;a.r-=cP(a,(sN(),pN))+i.a+(b?g.b+g.c:0);}e.e.i.a=j.a;e.e.i.b=j.b}}
function u$(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;k=new Wub;l=new Wub;q=new Wub;r=new Wub;j=Wv(rJ(b,(Rib(),Jib)),15).a;f=j*Wv(rJ(b,(Mjb(),qjb)),15).a;Ckb(Ixb(Xv(rJ(b,(eM(),rL)))));for(i=(m=(new Snb(c.a)).a.bb().mb(),new Ynb(m));i.a.G();){h=(g=Wv(i.a.H(),21),Wv(g.yb(),9));n=Wv(rJ(h,hib),32);if(n==(sN(),$M)){l.a.db(h,l);for(e=Uh(iX(h));Cm(e);){d=Wv(Dm(e),12);stb(k,d.c.f)}}else if(n==pN){r.a.db(h,r);for(e=Uh(iX(h));Cm(e);){d=Wv(Dm(e),12);stb(q,d.c.f)}}}if(k.a.Y()!=0){o=new cdb(2,f);p=bdb(o,b,k,l,-j-b.d.b);if(p>0){a.a=j+(p-1)*f;b.d.b+=a.a;b.e.b+=a.a}}if(q.a.Y()!=0){o=new cdb(1,f);p=bdb(o,b,q,r,b.e.b+j-b.d.b);p>0&&(b.e.b+=j+(p-1)*f)}}
function Xt(a,b){var c,d,e,f,g,h,i,j,k;if((bmb(),b.length)==0){return a.fc(Yxb,Xxb,-1,-1)}k=hmb(b);emb(k.substr(0,3),'at ')&&(k=imb(k,3,k.length-3));k=k.replace(/\[.*?\]/g,'');g=k.indexOf('(');if(g==-1){g=k.indexOf('@');if(g==-1){j=k;k=''}else{j=hmb(imb(k,g+1,k.length-(g+1)));k=hmb(k.substr(0,g))}}else{c=k.indexOf(')',g);j=k.substr(g+1,c-(g+1));k=hmb(k.substr(0,g))}g=mmb(k,lmb(46));g!=-1&&(k=imb(k,g+1,k.length-(g+1)));(k.length==0||emb(k,'Anonymous function'))&&(k=Xxb);h=nmb(j,lmb(58));e=omb(j,lmb(58),h-1);i=-1;d=-1;f=Yxb;if(h!=-1&&e!=-1){f=j.substr(0,e);i=St(j.substr(e+1,h-(e+1)));d=St(imb(j,h+1,j.length-(h+1)))}return a.fc(f,k,i,d)}
function idb(a){var b,c,d,e,f,g,h,i,j,k;j=new GU;h=new GU;for(g=new Tob(a);g.a<g.c.c.length;){e=Wv(Rob(g),80);e.c=e.b.c.length;e.f=e.e.c.length;e.c==0&&(j.c[j.c.length]=e,true);e.f==0&&e.j.b==0&&(h.c[h.c.length]=e,true)}d=-1;while(j.c.length!=0){e=Wv(AU(j,0),80);for(c=new Tob(e.e);c.a<c.c.c.length;){b=Wv(Rob(c),118);k=b.b;k.i=Plb(k.i,e.i+1);d=Plb(d,k.i);--k.c;k.c==0&&(j.c[j.c.length]=k,true)}}if(d>-1){for(f=new Tob(h);f.a<f.c.c.length;){e=Wv(Rob(f),80);e.i=d}while(h.c.length!=0){e=Wv(AU(h,0),80);for(c=new Tob(e.b);c.a<c.c.c.length;){b=Wv(Rob(c),118);i=b.a;if(i.j.b>0){continue}i.i=Slb(i.i,e.i-1);--i.f;i.f==0&&(h.c[h.c.length]=i,true)}}}}
function PV(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p;if(!Ckb(Ixb(Xv(rJ(c,(eM(),$L)))))){return}for(h=new Tob(c.f);h.a<h.c.c.length;){g=Wv(Rob(h),7);l=Wv(FU(g.e,xv(dB,gAb,12,g.e.c.length,0,1)),47);for(j=0,k=l.length;j<k;++j){i=l[j];f=i.d.f==c;e=f&&Ckb(Ixb(Xv(rJ(i,$L))));if(e){n=i.c;m=Wv(Smb(a.b,n),9);if(!m){m=NW(n,(KM(),IM),n.g,-1,n.j,Wv(rJ(b,sL),59),b);sJ(m,(Rib(),uib),n);Umb(a.b,n,m);vU(b.b,m)}p=i.d;o=Wv(Smb(a.b,p),9);if(!o){o=NW(p,(KM(),IM),p.g,1,p.j,Wv(rJ(b,sL),59),b);sJ(o,(Rib(),uib),p);Umb(a.b,p,o);vU(b.b,o)}d=IV(i);dW(d,Wv(yU(m.f,0),7));eW(d,Wv(yU(o.f,0),7));Fd(a.a,i,new XV(d,b,(djb(),bjb)));Wv(rJ(b,(Rib(),jib)),18).ib((ohb(),hhb))}}}}
function vfb(a,b,c,d,e,f){var g,h,i,j,k,l,m,n,o,p,q,r,s,t;n=sgb(a.g);p=sgb(c.g);o=vI(xI(a.i),a.a);q=vI(xI(c.i),c.a);g=vI(new II(o),CI(new GI(n),b));h=vI(new II(q),CI(new GI(p),d));j=ogb(a,e);e==(sN(),pN)||e==ZM?(j+=f):(j-=f);m=new FI;r=new FI;switch(e.e){case 1:case 3:m.a=g.a;m.b=o.b+j;r.a=h.a;r.b=m.b;break;case 2:case 4:m.a=o.a+j;m.b=g.b;r.a=m.a;r.b=h.b;break;default:return null;}k=CI(vI(new HI(m.a,m.b),r),0.5);l=new ufb(Bv(tv(qz,1),Fzb,10,0,[o,g,m,k,r,h,q]));i=ifb(l);t=jfb(l);switch(e.e){case 1:case 3:l.a=i;s=lfb(l);break;case 2:case 4:l.a=t;s=kfb(l);break;default:return null;}bfb(l,new Ffb(Bv(tv(qz,1),Fzb,10,0,[i,t,s,o,q])));return l}
function qU(a,b,c,d){var e,f,g,h,i,j,k,l,m,n;f=new eV(b);l=lU(a,b,f);n=Nlb(Wv(rJ(b,(eM(),dM)),15).a,1);for(k=new Tob(l.a);k.a<k.c.c.length;){j=Wv(Rob(k),27);i=pU(Wv(j.a,10),Wv(j.b,10),n);o=true;o=o&YU(c,new HI(i.d,i.e));o=o&YU(c,uI(new HI(i.d,i.e),i.c,0));o=o&YU(c,uI(new HI(i.d,i.e),0,i.b));o&YU(c,uI(new HI(i.d,i.e),i.c,i.b))}m=f.d;h=pU(Wv(l.b.a,10),Wv(l.b.b,10),n);if(m==(sN(),rN)||m==ZM){d.c[m.e]=Qlb(d.c[m.e],h.e);d.b[m.e]=Nlb(d.b[m.e],h.e+h.b)}else{d.c[m.e]=Qlb(d.c[m.e],h.d);d.b[m.e]=Nlb(d.b[m.e],h.d+h.c)}e=Vzb;g=f.c.f.e;switch(m.e){case 4:e=g.c;break;case 2:e=g.b;break;case 1:e=g.a;break;case 3:e=g.d;}d.a[m.e]=Nlb(d.a[m.e],e);return f}
function OV(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q;f=new GU;for(j=new Tob(d);j.a<j.c.c.length;){h=Wv(Rob(j),187);g=null;if(h.f==(djb(),bjb)){for(o=new Tob(h.e);o.a<o.c.c.length;){n=Wv(Rob(o),12);q=n.d.f;if(hX(q)==b){GV(a,b,h,n,h.b,n.d)}else if(!c||SW(q,c)){HV(a,b,h,d,n)}else{m=LV(a,b,c,n,h.b,bjb,g);m!=g&&(f.c[f.c.length]=m,true);m.c&&(g=m)}}}else{for(l=new Tob(h.e);l.a<l.c.c.length;){k=Wv(Rob(l),12);p=k.c.f;if(hX(p)==b){GV(a,b,h,k,k.c,h.b)}else if(!c||SW(p,c)){continue}else{m=LV(a,b,c,k,h.b,ajb,g);m!=g&&(f.c[f.c.length]=m,true);m.c&&(g=m)}}}}for(i=new Tob(f);i.a<i.c.c.length;){h=Wv(Rob(i),187);zU(b.b,h.a,0)!=-1||vU(b.b,h.a);h.c&&(e.c[e.c.length]=h,true)}}
function TO(a){var b,c,d,e;b=a.e.j;for(d=new Tob(AW(a));d.a<d.c.c.length;){c=Wv(Rob(d),161);e=Wv(oW(c,(eM(),LL)),15);!e&&(e=new llb(0));switch(Wv(c.e,7).g.e){case 4:c.e.i.b=b.b*Ixb(Yv(oW(c,HO)));c.e.i.a=-c.e.j.a-e.a;break;case 2:c.e.i.b=b.b*Ixb(Yv(oW(c,HO)));c.e.i.a=b.a+e.a;break;case 1:c.e.i.a=b.a*Ixb(Yv(oW(c,HO)));c.e.i.b=-c.e.j.b-e.a;break;case 3:c.e.i.a=b.a*Ixb(Yv(oW(c,HO)));c.e.i.b=b.b+e.a;}switch(Wv(c.e,7).g.e){case 4:c.e.i.b=b.b*Ixb(Yv(oW(c,HO)));c.e.i.a=-c.e.j.a-e.a;break;case 2:c.e.i.b=b.b*Ixb(Yv(oW(c,HO)));c.e.i.a=b.a+e.a;break;case 1:c.e.i.a=b.a*Ixb(Yv(oW(c,HO)));c.e.i.b=-c.e.j.b-e.a;break;case 3:c.e.i.a=b.a*Ixb(Yv(oW(c,HO)));c.e.i.b=b.b+e.a;}}}
function C2(a){var b,c,d,e,f,g,h,i,j;f=a.f;e=pr(Zdb(a));j=WI(Eo(a.g),0);while(j.b!=j.d.c){i=Wv(_ub(j),7);if(i.e.c.length==0){for(c=new Tob(i.b);c.a<c.c.c.length;){b=Wv(Rob(c),12);d=b.c;if(e.a.R(d)){g=new Fnb(f.f,0);h=(Bxb(g.b<g.d.Y()),Wv(g.d.sb(g.c=g.b++),7));while(h!=i){h=(Bxb(g.b<g.d.Y()),Wv(g.d.sb(g.c=g.b++),7))}Anb(g,d);$ub(j,d);J2(d,i.g);avb(j);avb(j);e.a.eb(d)!=null}}}else{for(c=new Tob(i.e);c.a<c.c.c.length;){b=Wv(Rob(c),12);d=b.d;if(e.a.R(d)){g=new Fnb(f.f,0);h=(Bxb(g.b<g.d.Y()),Wv(g.d.sb(g.c=g.b++),7));while(h!=i){h=(Bxb(g.b<g.d.Y()),Wv(g.d.sb(g.c=g.b++),7))}Bxb(g.b>0);g.a.sb(g.c=--g.b);Anb(g,d);$ub(j,d);J2(d,i.g);avb(j);avb(j);e.a.eb(d)!=null}}}}}
function IP(b){var c,d,e,f,g,h,i,j,k;g=new Uu(b);f=Pu(g,'graph');j=Pu(g,'success');e=Pu(g,'error');h=Pu(g,'options');try{if(!f||!f.kc()){throw new $J("Mandatory parameter missing, 'graph' must be specified")}AQ(new CQ,f.kc(),h?h.kc():null);i=f.kc().a;!!j&&!!j.kc()?HP(j.kc().a,i):HP(null,i)}catch(a){a=OH(a);if(aw(a,73)){k=a;!!e&&!!e.kc()?HP(e.kc().a,DQ(k).a):HP(null,DQ(k).a)}else if(aw(a,54)){c=a;d=new Tu;Ru(d,'type',new lv(Ikb(c.$c)));c.bc()!=null?Ru(d,Dzb,new lv(c.bc())):Ru(d,Dzb,new lv('null (sic)'));Ru(d,Ezb,new lv(Hb(new Kb('\n'),new wnb(new opb((c.g==null&&(c.g=Pt(c)),c.g))))));!!e&&!!e.kc()?HP(e.kc().a,d.a):HP(null,d.a);at(c,(Fmb(),Dmb),'')}else throw NH(a)}}
function e9(a,b,c){var d,e,f,g,h,i,j,k,l,m;if(c){d=-1;k=new Fnb(b,0);while(k.b<k.d.Y()){h=(Bxb(k.b<k.d.Y()),Wv(k.d.sb(k.c=k.b++),9));l=a.a[h.d.k][h.k].a;if(l==null){g=d+1;f=new Fnb(b,k.b);while(f.b<f.d.Y()){m=i9(a,(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),9))).a;if(m!=null){g=(Dxb(m),m);break}}l=(d+g)/2;a.a[h.d.k][h.k].a=l;a.a[h.d.k][h.k].d=(Dxb(l),l);a.a[h.d.k][h.k].b=1}d=(Dxb(l),l)}}else{e=0;for(j=new Tob(b);j.a<j.c.c.length;){h=Wv(Rob(j),9);a.a[h.d.k][h.k].a!=null&&(e=Nlb(e,Ixb(a.a[h.d.k][h.k].a)))}e+=2;for(i=new Tob(b);i.a<i.c.c.length;){h=Wv(Rob(i),9);if(a.a[h.d.k][h.k].a==null){l=wvb(a.e,24)*FAb*e-1;a.a[h.d.k][h.k].a=l;a.a[h.d.k][h.k].d=l;a.a[h.d.k][h.k].b=1}}}}
function RO(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o;i=0;j=0;o=0;n=0;g=0;m=0;l=0;k=0;for(f=new Lsb((new Fsb(a.c)).a);htb(f.a);){e=(f.b=itb(f.a),new Psb(f.c,f.b));d=Wv(e.b.b[e.a.e],62);switch(Wv(e.a,67).e){case 12:case 13:case 14:m+=d.c+b;break;case 15:case 16:case 17:l+=d.c+b;g=Nlb(g,d.b+b);break;case 18:case 19:case 20:k+=d.c+b;break;case 0:case 1:case 2:o+=d.c+b;break;case 3:case 4:case 5:n+=d.c+b;break;case 6:case 7:case 8:i+=d.b+b;break;case 9:case 10:case 11:j+=d.b+b;}}i-=b;j-=b;o-=b;n-=b;m+=m!=0?b:0;l+=l!=0?b:0;k+=k!=0?b:0;h=a.p.d+g+a.p.a;h+=h!=0?b:0;c.a=Nlb(c.a,o);c.a=Nlb(c.a,m);c.a=Nlb(c.a,l);c.a=Nlb(c.a,k);c.a=Nlb(c.a,n);c.b=Nlb(c.b,i);c.b=Nlb(c.b,h);c.b=Nlb(c.b,j)}
function T9(a){var b,c,d,e,f,g,h,i;b=null;for(d=new Tob(a);d.a<d.c.c.length;){c=Wv(Rob(d),102);Ixb(W9(c.g,c.d[0]).a);c.b=null;if(!!c.e&&c.e.Y()>0&&c.c==0){!b&&(b=new GU);b.c[b.c.length]=c}}if(b){while(b.c.length!=0){c=Wv(AU(b,0),102);if(!!c.b&&c.b.c.length>0){for(f=(!c.b&&(c.b=new GU),new Tob(c.b));f.a<f.c.c.length;){e=Wv(Rob(f),102);if(Ixb(W9(e.g,e.d[0]).a)==Ixb(W9(c.g,c.d[0]).a)){if(zU(a,e,0)>zU(a,c,0)){return new RJ(e,c)}}else if(Ixb(W9(e.g,e.d[0]).a)>Ixb(W9(c.g,c.d[0]).a)){return new RJ(e,c)}}}for(h=(!c.e&&(c.e=new GU),c.e).mb();h.G();){g=Wv(h.H(),102);i=(!g.b&&(g.b=new GU),g.b);Fxb(0,i.c.length);fxb(i.c,0,c);g.c==i.c.length&&(b.c[b.c.length]=g,true)}}}return null}
function R0(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p;l=(mp(),new ntb);for(k=(Il(),new Im(Dl(ul(a.a,new yl))));Cm(k);){j=Wv(Dm(k),9);e=Q0(j,(sN(),ZM));for(d=new Tob(e);d.a<d.c.c.length;){c=Wv(Rob(d),7);for(g=new Tob(c.e);g.a<g.c.c.length;){f=Wv(Rob(g),12);kP();p=f.d.f;(p.g==(CX(),zX)||p.g==yX)&&(p=Wv(rJ(p,(Rib(),rib)),7).f);if(Ktb(l.d,p)){b=Wv(re(Ktb(l.d,p)),171)}else{e.c.length==2?gw(c)===gw((Cxb(0,e.c.length),e.c[0]))?(b=gP):(b=hP):(b=gP);Ltb(l.d,p,b)}for(i=new Tob(f.b);i.a<i.c.c.length;){h=Wv(Rob(i),33);sJ(h,(Rib(),pib),b)}for(o=new Tob(f.c.c);o.a<o.c.c.length;){m=Wv(Rob(o),33);sJ(m,(Rib(),pib),b)}for(n=new Tob(f.d.c);n.a<n.c.c.length;){m=Wv(Rob(n),33);sJ(m,(Rib(),pib),b)}}}}}
function lZ(a,b){var c,d,e,f,g,h,i,j,k;if(tl(mX(b))!=1||Wv(ql(mX(b)),12).d.f.g!=(CX(),zX)){return null}f=Wv(ql(mX(b)),12);c=f.d.f;sX(c,(CX(),wX));sJ(c,(Rib(),qib),null);sJ(c,rib,null);sJ(c,(eM(),TL),Wv(rJ(b,TL),28));sJ(c,JL,Wv(rJ(b,JL),86));e=rJ(f.c,uib);g=null;for(j=nX(c,(sN(),ZM)).mb();j.G();){h=Wv(j.H(),7);if(h.e.c.length!=0){sJ(h,uib,e);k=f.c;h.j.a=k.j.a;h.j.b=k.j.b;h.a.a=k.a.a;h.a.b=k.a.b;xU(h.c,k.c);k.c.c=xv(UF,syb,1,0,4,1);g=h;break}}sJ(f.c,uib,null);if(!sl(nX(b,ZM))){for(i=new Tob(Ao(nX(b,ZM)));i.a<i.c.c.length;){h=Wv(Rob(i),7);if(h.e.c.length==0){d=new RX;QX(d,ZM);d.j.a=h.j.a;d.j.b=h.j.b;PX(d,c);sJ(d,uib,rJ(h,uib));PX(h,null)}else{PX(g,c)}}}c.j.b=b.j.b;vU(a.b,c);return c}
function _O(a){var b,c,d,e,f,g,h,i,j;f=a.e.e.j;g=new II(f);i=Wv(oW(a.e,(eM(),aM)),86);j=Wv(oW(a.e,bM),86);h=Wv(oW(a.e,TL),28);b=Zsb(i,(DN(),CN));if(i.c==0){return}f.a=0;f.b=0;d=null;switch(h.e){case 1:case 2:case 3:d=MO(a,a.k);break;case 4:d=new II(g);break;case 5:d=KO(a.e,b);}if(Zsb(i,BN)){if(d){f.a=Nlb(f.a,d.a);f.b=Nlb(f.b,d.b)}if(b){f.a=Nlb(f.a,a.q.b+a.q.c+a.k);f.b=Nlb(f.b,a.q.d+a.q.a+a.k)}}Zsb(i,AN)&&Qob(new Tob(zW(a.e)))&&RO(a,a.d,f);if(Zsb(i,zN)){e=Wv(oW(a.e,IL),15).a;c=Wv(oW(a.e,HL),15).a;if(Zsb(j,(MN(),KN))){e<=0&&(e=20);c<=0&&(c=20)}if(Zsb(j,LN)){e>0&&(f.a=Nlb(f.a,e+a.q.b+a.q.c));c>0&&(f.b=Nlb(f.b,c+a.q.d+a.q.a))}else{e>0&&(f.a=Nlb(f.a,e));c>0&&(f.b=Nlb(f.b,c))}}pW(a.e,f)}
function ewb(a,b,c){var d,e,f,g,h,i,j,k,l,m,n;if(!a.b){return false}g=null;m=null;i=new ywb(null,null);e=1;i.a[1]=a.b;l=i;while(l.a[e]){j=e;h=m;m=l;l=l.a[e];d=a.a.$b(b,l.d);e=d<0?0:1;d==0&&(!c.c||ovb(l.e,c.d))&&(g=l);if(!(!!l&&l.b)&&!awb(l.a[e])){if(awb(l.a[1-e])){m=m.a[j]=hwb(l,e)}else if(!awb(l.a[1-e])){n=m.a[1-j];if(n){if(!awb(n.a[1-j])&&!awb(n.a[j])){m.b=false;n.b=true;l.b=true}else{f=h.a[1]==m?1:0;awb(n.a[j])?(h.a[f]=gwb(m,j)):awb(n.a[1-j])&&(h.a[f]=hwb(m,j));l.b=h.a[f].b=true;h.a[f].a[0].b=false;h.a[f].a[1].b=false}}}}}if(g){c.b=true;c.d=g.e;if(l!=g){k=new ywb(l.d,l.e);fwb(a,i,g,k);m==g&&(m=k)}m.a[m.a[1]==l?1:0]=l.a[!l.a[0]?1:0];--a.c}a.b=i.a[1];!!a.b&&(a.b.b=false);return c.b}
function v$(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;d=Wv(rJ(a,(eM(),TL)),28);i=a.e;h=a.a;c=Wv(rJ(a,(Rib(),Xhb)),15).a;j=i.a+h.b+h.c+2*c;k=0-h.d-c-a.d.b;n=i.b+h.d+h.a+2*c-a.d.b;l=new GU;o=new GU;for(f=(m=(new Snb(b.a)).a.bb().mb(),new Ynb(m));f.a.G();){e=(g=Wv(f.a.H(),21),Wv(g.yb(),9));switch(d.e){case 1:case 2:case 3:m$(e);break;case 4:p=Wv(rJ(e,SL),10);q=!p?0:p.a;e.i.a=j*Ixb(Yv(rJ(e,Cib)))-q;fX(e,true,false);break;case 5:r=Wv(rJ(e,SL),10);s=!r?0:r.a;e.i.a=Ixb(Yv(rJ(e,Cib)))-s;fX(e,true,false);i.a=Nlb(i.a,e.i.a+e.j.a/2);}switch(Wv(rJ(e,hib),32).e){case 1:e.i.b=k;l.c[l.c.length]=e;break;case 3:e.i.b=n;o.c[o.c.length]=e;}}switch(d.e){case 1:case 2:o$(l,a);o$(o,a);break;case 3:t$(l,a);t$(o,a);}}
function OY(a){var b,c,d,e,f,g;d=Wv(rJ(a.a.g,(eM(),JL)),86);if(jf(d,(oM(),b=Wv(Hkb(Gz),11),new atb(b,Wv(exb(b,b.length),11),0))));else if(Xe(d,Usb(gM))){c=Wv(Wv(Dd(a.a.b,a.b),20).sb(0),33);a.b.i.a=c.i.a;a.b.i.b=c.i.b}else if(Xe(d,Usb(iM))){e=Wv(yU(a.a.c,a.a.c.c.length-1),9);f=Wv(Wv(Dd(a.a.b,a.b),20).sb(Wv(Dd(a.a.b,a.b),20).Y()-1),33);g=e.j.a-(f.i.a+f.j.a);a.b.i.a=a.a.g.j.a-g-a.b.j.a;a.b.i.b=f.i.b}else if(Xe(d,Vsb(mM,Bv(tv(Gz,1),uyb,41,0,[fM])))){c=Wv(Wv(Dd(a.a.b,a.b),20).sb(0),33);a.b.i.a=(a.a.g.j.a-a.b.j.a)/2;a.b.i.b=c.i.b}else if(Xe(d,Usb(mM))){c=Wv(Wv(Dd(a.a.b,a.b),20).sb(0),33);a.b.i.b=c.i.b}else if(Xe(d,Usb(fM))){c=Wv(Wv(Dd(a.a.b,a.b),20).sb(0),33);a.b.i.a=(a.a.g.j.a-a.b.j.a)/2;a.b.i.b=c.i.b}return null}
function NZ(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q;for(o=new Tob(a);o.a<o.c.c.length;){n=Wv(Rob(o),9);MZ(n.i);MZ(n.j);PZ(n);RZ(n);for(q=new Tob(n.f);q.a<q.c.c.length;){p=Wv(Rob(q),7);MZ(p.i);MZ(p.a);MZ(p.j);QX(p,QZ(p.g));f=Wv(rJ(p,(eM(),UL)),24);!!f&&sJ(p,UL,Elb(-f.a));for(e=new Tob(p.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);for(c=WI(d.a,0);c.b!=c.d.c;){b=Wv(_ub(c),10);MZ(b)}i=Wv(rJ(d,CL),44);if(i){for(h=WI(i,0);h.b!=h.d.c;){g=Wv(_ub(h),10);MZ(g)}}for(l=new Tob(d.b);l.a<l.c.c.length;){j=Wv(Rob(l),33);MZ(j.i);MZ(j.j)}}for(m=new Tob(p.c);m.a<m.c.c.length;){j=Wv(Rob(m),33);MZ(j.i);MZ(j.j)}}if(n.g==(CX(),xX)){sJ(n,(Rib(),hib),QZ(Wv(rJ(n,hib),32)));OZ(n)}for(k=new Tob(n.c);k.a<k.c.c.length;){j=Wv(Rob(k),33);MZ(j.j);MZ(j.i)}}}
function YP(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;TP(c);if(SW(b.d.f,b.c.f)){k=b.c;l=MI(Bv(tv(qz,1),Fzb,10,0,[k.i,k.a]));j=k.f.b;uI(l,-j.b,-j.d);l.a-=d.a;l.b-=d.b}else{l=MX(b.c)}l.a+=d.a;l.b+=d.b;m=new Tu;VP(a,m,'x',l.a);VP(a,m,'y',l.b);Ru(c,'sourcePoint',m);n=MX(b.d);rJ(b,(Rib(),Pib))!=null&&vI(n,Wv(rJ(b,Pib),10));vI(n,d);o=new Tu;VP(a,o,'x',n.a);VP(a,o,'y',n.b);Ru(c,'targetPoint',o);e=new ju;s=hJ(b.a,d);f=0;for(r=WI(s,0);r.b!=r.d.c;){p=Wv(_ub(r),10);i=new Tu;VP(a,i,'x',p.a);VP(a,i,'y',p.b);hu(e,f++,i)}s.b==0?Ru(c,Hzb,null):Ru(c,Hzb,e);g=Wv(rJ(b,(eM(),CL)),44);f=0;if(g){hJ(g,d);h=new ju;for(q=WI(g,0);q.b!=q.d.c;){p=Wv(_ub(q),10);i=new Tu;VP(a,i,'x',p.a);VP(a,i,'y',p.b);hu(h,f++,i)}Ru(c,Izb,h)}else{Ru(c,Izb,null)}}
function pZ(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r;p=a.i;q=a.j;m=a.e;if(b){l=d/2*(b.Y()-1);n=0;for(j=b.mb();j.G();){h=Wv(j.H(),9);l+=h.j.a;n=Nlb(n,h.j.b)}r=p.a-(l-q.a)/2;g=p.b-m.d+n;e=q.a/(b.Y()+1);f=e;for(i=b.mb();i.G();){h=Wv(i.H(),9);h.i.a=r;h.i.b=g-h.j.b;r+=h.j.a+d/2;k=oZ(h);k.i.a=h.j.a/2-k.a.a;k.i.b=h.j.b;o=Wv(rJ(h,(Rib(),Zhb)),7);if(o.b.c.length+o.e.c.length==1){o.i.a=f-o.a.a;o.i.b=0;PX(o,a)}f+=e}}if(c){l=d/2*(c.Y()-1);n=0;for(j=c.mb();j.G();){h=Wv(j.H(),9);l+=h.j.a;n=Nlb(n,h.j.b)}r=p.a-(l-q.a)/2;g=p.b+q.b+m.a-n;e=q.a/(c.Y()+1);f=e;for(i=c.mb();i.G();){h=Wv(i.H(),9);h.i.a=r;h.i.b=g;r+=h.j.a+d/2;k=oZ(h);k.i.a=h.j.a/2-k.a.a;k.i.b=0;o=Wv(rJ(h,(Rib(),Zhb)),7);if(o.b.c.length+o.e.c.length==1){o.i.a=f-o.a.a;o.i.b=q.b;PX(o,a)}f+=e}}}
function Jab(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w;w=0;n=0;for(l=new Tob(b.f);l.a<l.c.c.length;){k=Wv(Rob(l),9);m=0;h=0;i=c?Wv(rJ(k,Fab),24).a:eyb;r=d?Wv(rJ(k,Gab),24).a:eyb;j=i>r?i:r;for(t=new Tob(k.f);t.a<t.c.c.length;){s=Wv(Rob(t),7);u=k.i.b+s.i.b+s.a.b;if(d){for(g=new Tob(s.e);g.a<g.c.c.length;){f=Wv(Rob(g),12);p=f.d;o=p.f;if(b!=a.a[o.k]){q=Plb(Wv(rJ(o,Fab),24).a,Wv(rJ(o,Gab),24).a);v=Wv(rJ(f,(Rib(),Eib)),24).a;if(v>=j&&v>=q){m+=o.i.b+p.i.b+p.a.b-u;++h}}}}if(c){for(g=new Tob(s.b);g.a<g.c.c.length;){f=Wv(Rob(g),12);p=f.c;o=p.f;if(b!=a.a[o.k]){q=Plb(Wv(rJ(o,Fab),24).a,Wv(rJ(o,Gab),24).a);v=Wv(rJ(f,(Rib(),Eib)),24).a;if(v>=j&&v>=q){m+=o.i.b+p.i.b+p.a.b-u;++h}}}}}if(h>0){w+=m/h;++n}}if(n>0){b.a=e*w/n;b.i=n}else{b.a=0;b.i=0}}
function Kab(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;n=b.c.length;m=0;for(l=new Tob(a.c);l.a<l.c.c.length;){k=Wv(Rob(l),16);r=k.a;if(r.c.length==0){continue}q=new Tob(r);j=0;s=null;e=Wv(Rob(q),9);while(e){f=Wv(yU(b,e.k),111);if(f.c>=0){i=null;h=new Fnb(k.a,j+1);while(h.b<h.d.Y()){g=(Bxb(h.b<h.d.Y()),Wv(h.d.sb(h.c=h.b++),9));i=Wv(yU(b,g.k),111);if(i.d==f.d&&i.c<f.c){break}else{i=null}}if(i){if(s){DU(d,e.k,Elb(Wv(yU(d,e.k),24).a-1));Wv(yU(c,s.k),20).nb(f)}f=Vab(f,e,n++);b.c[b.c.length]=f;vU(c,new GU);if(s){Wv(yU(c,s.k),20).ib(f);vU(d,Elb(1))}else{vU(d,Elb(0))}}}o=null;if(q.a<q.c.c.length){o=Wv(Rob(q),9);p=Wv(yU(b,o.k),111);Wv(yU(c,e.k),20).ib(p);DU(d,o.k,Elb(Wv(yU(d,o.k),24).a+1))}f.d=m;f.c=j++;s=e;e=o}++m}Ckb(Ixb(Xv(rJ(a,(eM(),rL)))))&&undefined}
function gS(a,b){var c;if(a.e){throw new ulb((Gkb(nA),'The '+nA.j+Yzb))}if(!MR(a.a,b)){throw new gt('The direction '+b+' is not supported by the CGraph instance.')}if(b==a.d){return a}c=a.d;a.d=b;switch(c.e){case 0:switch(b.e){case 2:dS(a);break;case 1:kS(a);dS(a);break;case 4:qS(a);dS(a);break;case 3:qS(a);kS(a);dS(a);}break;case 2:switch(b.e){case 1:kS(a);lS(a);break;case 4:qS(a);dS(a);break;case 3:qS(a);kS(a);dS(a);}break;case 1:switch(b.e){case 2:kS(a);lS(a);break;case 4:kS(a);qS(a);dS(a);break;case 3:kS(a);qS(a);kS(a);dS(a);}break;case 4:switch(b.e){case 2:qS(a);dS(a);break;case 1:qS(a);kS(a);dS(a);break;case 3:kS(a);lS(a);}break;case 3:switch(b.e){case 2:kS(a);qS(a);dS(a);break;case 1:kS(a);qS(a);kS(a);dS(a);break;case 4:kS(a);lS(a);}}return a}
function c9(a,b,c){var d,e,f,g,h,i,j,k,l;if(a.a[b.d.k][b.k].e){return}else{a.a[b.d.k][b.k].e=true}a.a[b.d.k][b.k].b=0;a.a[b.d.k][b.k].d=0;a.a[b.d.k][b.k].a=null;for(k=new Tob(b.f);k.a<k.c.c.length;){j=Wv(Rob(k),7);l=c?new fY(j):new lY(j);for(i=l.mb();i.G();){h=Wv(i.H(),7);g=h.f;if(g.d==b.d){if(g!=b){c9(a,g,c);a.a[b.d.k][b.k].b+=a.a[g.d.k][g.k].b;a.a[b.d.k][b.k].d+=a.a[g.d.k][g.k].d}}else{a.a[b.d.k][b.k].d+=a.d[h.k];++a.a[b.d.k][b.k].b}}}f=Wv(rJ(b,(Rib(),Shb)),20);if(f){for(e=f.mb();e.G();){d=Wv(e.H(),9);if(b.d==d.d){c9(a,d,c);a.a[b.d.k][b.k].b+=a.a[d.d.k][d.k].b;a.a[b.d.k][b.k].d+=a.a[d.d.k][d.k].d}}}if(a.a[b.d.k][b.k].b>0){a.a[b.d.k][b.k].d+=wvb(a.e,24)*FAb*0.07000000029802322-0.03500000014901161;a.a[b.d.k][b.k].a=a.a[b.d.k][b.k].d/a.a[b.d.k][b.k].b}}
function Sbb(a,b){var c,d,e,f,g,h,i,j,k,l,m;for(e=new Tob(a.a.c);e.a<e.c.c.length;){c=Wv(Rob(e),16);for(i=new Tob(c.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);b.i[h.k]=h;b.g[h.k]=b.k==(Lbb(),Kbb)?Vzb:Uzb}}g=a.a.c;b.c==(Gbb(),Ebb)&&(g=aw(g,87)?Ii(Wv(g,87)):aw(g,88)?Wv(g,88).a:aw(g,63)?new ap(g):new Ro(g));Acb(a.e,b,a.b);bpb(b.n);for(f=g.mb();f.G();){c=Wv(f.H(),16);j=c.a;b.k==(Lbb(),Kbb)&&(j=aw(j,87)?Ii(Wv(j,87)):aw(j,88)?Wv(j,88).a:aw(j,63)?new ap(j):new Ro(j));for(m=j.mb();m.G();){l=Wv(m.H(),9);b.f[l.k]==l&&Tbb(a,l,b)}}Ubb(a,b);for(d=g.mb();d.G();){c=Wv(d.H(),16);for(m=new Tob(c.a);m.a<m.c.c.length;){l=Wv(Rob(m),9);b.n[l.k]=b.n[b.f[l.k].k];if(l==b.f[l.k]){k=Ixb(b.g[b.i[l.k].k]);(b.k==(Lbb(),Kbb)&&k>Vzb||b.k==Jbb&&k<Uzb)&&(b.n[l.k]=Ixb(b.n[l.k])+k)}}}a.e.Jc()}
function NQ(a,b){var c,d,e,f,g,h,i,j,k,l,m;pJ(b,Bv(tv(rz,1),syb,79,0,[(Rib(),Jib),Xhb,(Mjb(),Kjb),Rhb]));j=Wv(rJ(b,Jib),15).a;Wv(rJ(b,qjb),15).a*j<2&&sJ(b,qjb,new llb(2/j));k=Wv(rJ(b,(eM(),sL)),59);k==(sK(),qK)&&sJ(b,sL,PW(b));l=Wv(rJ(b,Hjb),24);l.a==0?sJ(b,Gib,new yvb):sJ(b,Gib,new zvb(l.a));m=new $jb(b);sJ(b,Kib,m);e=KQ(a,Wv(rJ(b,ljb),180));h=KQ(a,Wv(rJ(b,zjb),180));d=KQ(a,Wv(rJ(b,kjb),180));i=KQ(a,Wv(rJ(b,Ajb),180));f=KQ(a,Ocb(Wv(rJ(b,eib),122)));g=new WQ;sJ(b,_hb,g);QQ(QQ(QQ(QQ(QQ(QQ(g,e.qc(b)),h.qc(b)),d.qc(b)),i.qc(b)),f.qc(b)),MQ(b));c=(Mh(30,Vyb),new HU(30));sJ(b,Fib,c);xU(c,LQ(a,g,0));c.c[c.c.length]=e;xU(c,LQ(a,g,1));c.c[c.c.length]=h;xU(c,LQ(a,g,2));c.c[c.c.length]=d;xU(c,LQ(a,g,3));c.c[c.c.length]=i;xU(c,LQ(a,g,4));c.c[c.c.length]=f;xU(c,LQ(a,g,5))}
function YO(a,b){var c,d,e,f,g,h;f=Li(DW(a));if(f.Nb().V()){return}e=Wv(rJ(Wv(Wv(Wv(f.Nb().sb(0),129),224).e,33),(kP(),iP)),171);e=e==jP?hP:e;h=0;switch(Wv(a.e,7).g.e){case 4:case 2:e==hP&&(h=a.e.j.b);break;case 3:h=a.e.j.b;}(Wv(a.e,7).g==(sN(),$M)||e==gP)&&(f=Ii(f));for(d=Xl(f.Nb().mb());d.G();){c=Wv(d.H(),129);g=new II(c.e.i);if(e==gP){switch(Wv(a.e,7).g.e){case 1:case 4:g.a=-c.e.j.a-b;g.b=h-b-c.e.j.b;h-=b+c.e.j.b;break;case 2:g.a=a.e.j.a+b;g.b=h-b-c.e.j.b;h-=b+c.e.j.b;break;case 3:g.a=-c.e.j.a-b;g.b=h+b;h+=b+c.e.j.b;}}else{switch(Wv(a.e,7).g.e){case 4:g.a=-c.e.j.a-b;g.b=h+b;h+=b+c.e.j.b;break;case 2:g.a=a.e.j.a+b;g.b=h+b;h+=b+c.e.j.b;break;case 1:g.a=a.e.j.a+b;g.b=h-b-c.e.j.b;h-=b+c.e.j.b;break;case 3:g.a=a.e.j.a+b;g.b=h+b;h+=b+c.e.j.b;}}c.e.i.a=g.a;c.e.i.b=g.b}}
function fab(a,b,c){var d,e,f,g,h,i,j,k,l,m,n;d=0;e=0;for(k=0;k<a.length;k++){i=a[k];if(LM(Wv(rJ(i,(eM(),TL)),28))){for(g=nX(i,(sN(),ZM)).mb();g.G();){f=Wv(g.H(),7);if(f.b.c.length+f.e.c.length>0){d+=f.b.c.length+f.e.c.length;Umb(b,f,Elb(d))}}}else{for(h=nX(i,(sN(),ZM)).mb();h.G();){f=Wv(h.H(),7);d+=f.b.c.length+f.e.c.length}for(g=nX(i,ZM).mb();g.G();){f=Wv(g.H(),7);f.b.c.length+f.e.c.length>0&&Umb(b,f,Elb(d))}}}for(j=a.length-1;j>=0;j--){i=a[j];if(LM(Wv(rJ(i,(eM(),TL)),28))){for(m=nX(i,(sN(),rN)).mb();m.G();){l=Wv(m.H(),7);if(l.b.c.length+l.e.c.length>0){e+=l.b.c.length+l.e.c.length;Umb(c,l,Elb(e))}}}else{for(n=nX(i,(sN(),rN)).mb();n.G();){l=Wv(n.H(),7);e+=l.b.c.length+l.e.c.length}for(m=nX(i,rN).mb();m.G();){l=Wv(m.H(),7);l.b.c.length+l.e.c.length>0&&Umb(c,l,Elb(e))}}}}
function wfb(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r;m=sgb(a.g);o=sgb(b.g);n=vI(xI(a.i),a.a);p=vI(xI(b.i),b.a);i=vI(new HI(n.a,n.b),CI(new GI(m),1.3*c));q=vI(new HI(p.a,p.b),CI(new GI(o),1.3*d));h=Jlb(i.a-q.a);h<e&&(a.g==(sN(),rN)||a.g==ZM?i.a<q.a?(i.a=q.a-e):(i.a=q.a+e):i.a<q.a?(q.a=i.a+e):(q.a=i.a-e));f=0;g=0;switch(a.g.e){case 4:f=2*(n.a-c)-0.5*(i.a+q.a);break;case 2:f=2*(n.a+c)-0.5*(i.a+q.a);break;case 1:g=2*(n.b-c)-0.5*(i.b+q.b);break;case 3:g=2*(n.b+c)-0.5*(i.b+q.b);}switch(b.g.e){case 4:f=2*(p.a-d)-0.5*(q.a+i.a);break;case 2:f=2*(p.a+d)-0.5*(q.a+i.a);break;case 1:g=2*(p.b-d)-0.5*(q.b+i.b);break;case 3:g=2*(p.b+d)-0.5*(q.b+i.b);}l=new HI(f,g);k=new ufb(Bv(tv(qz,1),Fzb,10,0,[n,i,l,q,p]));j=ifb(k);r=jfb(k);k.a=j;bfb(k,new Ffb(Bv(tv(qz,1),Fzb,10,0,[j,r,n,p])));return k}
function p$(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q;i=c.a;e=Wv(rJ(c,(Rib(),Xhb)),15).a;o=c.d;h=(d=Wv(rJ(c,Xhb),15).a,new HI(c.e.a+c.a.b+c.a.c+2*d,c.e.b+c.a.d+c.a.a+2*d));j=h.b;for(m=new Tob(a.a);m.a<m.c.c.length;){k=Wv(Rob(m),9);if(k.g!=(CX(),xX)){continue}f=Wv(rJ(k,hib),32);g=Wv(rJ(k,iib),10);n=k.i;switch(f.e){case 2:n.a=c.e.a+e+i.c-o.a;break;case 4:n.a=-o.a-e-i.b;}q=0;switch(f.e){case 2:case 4:if(b==(KM(),GM)){p=Ixb(Yv(rJ(k,Cib)));n.b=h.b*p-Wv(rJ(k,(eM(),SL)),10).b;q=n.b+g.b;fX(k,false,true)}else if(b==FM){n.b=Ixb(Yv(rJ(k,Cib)))-Wv(rJ(k,(eM(),SL)),10).b;q=n.b+g.b;fX(k,false,true)}}j=j>q?j:q}c.e.b+=j-h.b;for(l=new Tob(a.a);l.a<l.c.c.length;){k=Wv(Rob(l),9);if(k.g!=(CX(),xX)){continue}f=Wv(rJ(k,hib),32);n=k.i;switch(f.e){case 1:n.b=-o.b-e-i.d;break;case 3:n.b=c.e.b+e+i.a-o.b;}}}
function $Y(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o;e=new GU;for(i=new Tob(a.d.f);i.a<i.c.c.length;){g=Wv(Rob(i),7);g.g==(sN(),ZM)&&(e.c[e.c.length]=g,true)}if(a.e.a==(sK(),pK)&&!MM(Wv(rJ(a.d,(eM(),TL)),28))){for(d=Uh(mX(a.d));Cm(d);){c=Wv(Dm(d),12);vU(e,c.c)}}f=a.d.j.a;sJ(a.d,(Rib(),Whb),new llb(a.d.j.a));a.d.j.a=a.c;sJ(a.d,Vhb,(xkb(),xkb(),wkb));vU(a.b,a.d);j=a.d;f-=a.c;k=a.a;while(k>1){b=Qlb(f,a.c);j=(l=new uX(a.e.c),sX(l,(CX(),wX)),sJ(l,(eM(),TL),Wv(rJ(j,TL),28)),sJ(l,JL,Wv(rJ(j,JL),86)),l.k=a.e.b++,vU(a.b,l),l.j.b=j.j.b,l.j.a=b,m=new RX,QX(m,(sN(),ZM)),PX(m,j),m.i.a=l.j.a,m.i.b=l.j.b/2,n=new RX,QX(n,rN),PX(n,l),n.i.b=l.j.b/2,n.i.a=-n.j.a,o=new hW,dW(o,m),eW(o,n),l);vU(a.e.c.b,j);--k;f-=a.c+a.e.d}new HY(a.d,a.b,a.c);for(h=new Tob(e);h.a<h.c.c.length;){g=Wv(Rob(h),7);BU(a.d.f,g);PX(g,j)}}
function Qfb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n;if(a.p>b.a||b.p>a.a){return}c=0;d=0;for(l=(g=(new Snb(a.o.a)).a.bb().mb(),new Ynb(g));l.a.G();){j=(e=Wv(l.a.H(),21),Wv(e.yb(),7));qgb(MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b,b.p,b.a)&&++c}for(m=(h=(new Snb(a.g.a)).a.bb().mb(),new Ynb(h));m.a.G();){j=(e=Wv(m.a.H(),21),Wv(e.yb(),7));qgb(MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b,b.p,b.a)&&--c}for(n=(i=(new Snb(b.o.a)).a.bb().mb(),new Ynb(i));n.a.G();){j=(e=Wv(n.a.H(),21),Wv(e.yb(),7));qgb(MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b,a.p,a.a)&&++d}for(k=(f=(new Snb(b.g.a)).a.bb().mb(),new Ynb(f));k.a.G();){j=(e=Wv(k.a.H(),21),Wv(e.yb(),7));qgb(MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b,a.p,a.a)&&--d}if(c<d){new bgb(a,b,d-c)}else if(d<c){new bgb(b,a,c-d)}else{new bgb(b,a,0);new bgb(a,b,0)}}
function $jb(a){var b;this.f=Wv(rJ(a,(Rib(),Jib)),15).a;this.d=Wv(rJ(a,(Mjb(),Ejb)),15).a;this.a=this.f*Wv(rJ(a,qjb),15).a;this.b=this.f*Wv(rJ(a,pjb),15).a;Wv(rJ(a,Dib),15);this.c=Wv(rJ(a,Dib),15).a;this.e=Wv(rJ(a,(eM(),DL)),15).a;b=(CX(),Bv(tv(pB,1),uyb,132,0,[AX,zX,xX,BX,yX,wX])).length;this.g=vv(lw,[Txb,tAb],[250,26],12,[b,b],2);Yjb(this,AX,this.f);Zjb(this,AX,zX,this.b);Zjb(this,AX,BX,this.b);Zjb(this,AX,xX,this.c);Zjb(this,AX,yX,this.b);Zjb(this,AX,wX,this.b);Yjb(this,zX,this.a);Zjb(this,zX,BX,this.a);Zjb(this,zX,xX,this.c);Zjb(this,zX,yX,this.e);Zjb(this,zX,wX,this.b);Yjb(this,BX,this.a);Zjb(this,BX,xX,this.c);Zjb(this,BX,yX,this.e);Zjb(this,BX,wX,this.b);Yjb(this,xX,this.c);Zjb(this,xX,yX,this.c);Zjb(this,xX,wX,this.c);Yjb(this,yX,this.e);Zjb(this,yX,wX,this.e);Yjb(this,wX,this.f)}
function mZ(a,b){var c,d,e,f,g,h,i,j,k;if(tl(iX(b))!=1||Wv(ql(iX(b)),12).c.f.g!=(CX(),zX)){return null}c=Wv(ql(iX(b)),12);d=c.c.f;sX(d,(CX(),AX));sJ(d,(Rib(),qib),null);sJ(d,rib,null);sJ(d,Whb,Wv(rJ(b,Whb),15));sJ(d,Vhb,(xkb(),xkb(),wkb));sJ(d,uib,rJ(b,uib));d.j.b=b.j.b;f=rJ(c.d,uib);g=null;for(j=nX(d,(sN(),rN)).mb();j.G();){h=Wv(j.H(),7);if(h.b.c.length!=0){sJ(h,uib,f);k=c.d;h.j.a=k.j.a;h.j.b=k.j.b;h.a.a=k.a.a;h.a.b=k.a.b;xU(h.c,k.c);k.c.c=xv(UF,syb,1,0,4,1);g=h;break}}sJ(c.d,uib,null);if(tl(nX(b,rN))>1){for(i=WI(Eo(nX(b,rN)),0);i.b!=i.d.c;){h=Wv(_ub(i),7);if(h.b.c.length==0){e=new RX;QX(e,rN);e.j.a=h.j.a;e.j.b=h.j.b;PX(e,d);sJ(e,uib,rJ(h,uib));PX(h,null)}else{PX(g,d)}}}sJ(b,uib,null);sJ(b,Vhb,(null,vkb));sX(b,wX);sJ(d,(eM(),TL),Wv(rJ(b,TL),28));sJ(d,JL,Wv(rJ(b,JL),86));uU(a.b,0,d);return d}
function NW(a,b,c,d,e,f,g){var h,i,j,k,l,m;l=c;j=new uX(g);sX(j,(CX(),xX));sJ(j,(Rib(),iib),e);sJ(j,(eM(),TL),(KM(),FM));sJ(j,tib,Wv(rJ(a,LL),15));i=Wv(rJ(a,SL),10);!i&&(i=new HI(e.a/2,e.b/2));sJ(j,SL,i);k=new RX;PX(k,j);if(!(b!=IM&&b!=JM)){h=f!=(sK(),qK)?f:pK;d>0?(l=vN(h)):(l=tN(vN(h)));sJ(a,WL,l)}switch(l.e){case 4:sJ(j,(Mjb(),vjb),(Xib(),Tib));sJ(j,dib,(Hgb(),Ggb));j.j.b=e.b;QX(k,(sN(),ZM));k.i.b=i.b;break;case 2:sJ(j,(Mjb(),vjb),(Xib(),Vib));sJ(j,dib,(Hgb(),Egb));j.j.b=e.b;QX(k,(sN(),rN));k.i.b=i.b;break;case 1:sJ(j,mib,(Hhb(),Ghb));j.j.a=e.a;QX(k,(sN(),pN));k.i.a=i.a;break;case 3:sJ(j,mib,(Hhb(),Ehb));j.j.a=e.a;QX(k,(sN(),$M));k.i.a=i.a;}if(b==EM||b==GM||b==FM){m=0;switch(l.e){case 4:case 2:m=null.cd;b==GM&&(m/=null.cd);break;case 1:case 3:m=null.cd;b==GM&&(m/=null.cd);}sJ(j,Cib,m)}sJ(j,hib,l);return j}
function LP(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;j=new jJ;r=(mp(),new ntb);Umb(r,a,MP(a));d=(Mh(2,Vyb),new HU(2));!!a.c&&vU(d,a.c);!!a.d&&vU(d,a.d);for(n=new Tob(d);n.a<n.c.c.length;){m=Wv(Rob(n),7);b=new aJ;Ue(b,Ao(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[m.b,m.e])))))));Ve(b,a,true);if(b.b!=0){t=Wv(re(Ktb(r.d,a)),34);if(m==a.d){o=t[t.length-1];s=true}else{o=t[0];s=false}for(i=1;i<t.length;i++){s?(p=t[t.length-1-i]):(p=t[i]);c=WI(b,0);while(c.b!=c.d.c){k=Wv(_ub(c),12);l=Wv(re(Ktb(r.d,k)),34);if(l==null){l=MP(k);Ltb(r.d,k,l)}if(l.length<=i){bvb(c)}else{s?(q=l[l.length-1-i]):(q=l[i]);if(p.a!=q.a||p.b!=q.b){e=p.a-o.a;g=p.b-o.b;f=q.a-o.a;h=q.b-o.b;f*g==h*e&&NP(e)==NP(f)&&NP(g)==NP(h)?((e<=0?0-e:e)<(f<=0?0-f:f)||(g<=0?0-g:g)<(h<=0?0-h:h))&&(TI(j,p,j.c.b,j.c),true):i>1&&(TI(j,o,j.c.b,j.c),true);bvb(c)}}}o=p}}}return j}
function m1(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p;a.n=Wv(rJ(a.g,(Rib(),Jib)),15).a*Wv(rJ(a.g,(Mjb(),Ejb)),15).a;a.e=a.n*Wv(rJ(a.g,qjb),15).a;a.i=a.g.c.c.length;h=a.i-1;m=0;a.j=0;a.k=0;a.a=Co(xv(PF,Txb,24,a.i,0,1));a.b=Co(xv(HF,Txb,184,a.i,6,1));for(g=new Tob(a.g.c);g.a<g.c.c.length;){e=Wv(Rob(g),16);e.k=h;for(l=new Tob(e.a);l.a<l.c.c.length;){k=Wv(Rob(l),9);k.k=m;++m}--h}a.f=xv(mw,Yyb,26,m,12,1);a.c=vv(mw,[Txb,Yyb],[52,26],12,[m,3],2);a.o=new GU;a.p=new GU;b=0;a.d=0;for(f=new Tob(a.g.c);f.a<f.c.c.length;){e=Wv(Rob(f),16);h=e.k;d=0;p=0;i=e.a.c.length;j=0;for(l=new Tob(e.a);l.a<l.c.c.length;){k=Wv(Rob(l),9);m=k.k;a.f[m]=k.d.k;j+=k.j.b+a.n;c=tl(iX(k));o=tl(mX(k));a.c[m][0]=o-c;a.c[m][1]=c;a.c[m][2]=o;d+=c;p+=o;c>0&&vU(a.p,k);vU(a.o,k)}b-=d;n=i+b;j+=b*a.e;DU(a.a,h,Elb(n));DU(a.b,h,j);a.j=Plb(a.j,n);a.k=Nlb(a.k,j);a.d+=b;b+=p}}
function sN(){sN=iI;var a;qN=new uN(szb,0);$M=new uN('NORTH',1);ZM=new uN('EAST',2);pN=new uN('SOUTH',3);rN=new uN('WEST',4);dN=(ypb(),new Frb((a=Wv(Hkb(Kz),11),new atb(a,Wv(exb(a,a.length),11),0))));eN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[])));_M=Kk(Vsb(ZM,Bv(tv(Kz,1),uyb,32,0,[])));mN=Kk(Vsb(pN,Bv(tv(Kz,1),uyb,32,0,[])));oN=Kk(Vsb(rN,Bv(tv(Kz,1),uyb,32,0,[])));jN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[pN])));cN=Kk(Vsb(ZM,Bv(tv(Kz,1),uyb,32,0,[rN])));lN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[rN])));fN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[ZM])));nN=Kk(Vsb(pN,Bv(tv(Kz,1),uyb,32,0,[rN])));aN=Kk(Vsb(ZM,Bv(tv(Kz,1),uyb,32,0,[pN])));iN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[ZM,rN])));bN=Kk(Vsb(ZM,Bv(tv(Kz,1),uyb,32,0,[pN,rN])));kN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[pN,rN])));gN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[ZM,pN])));hN=Kk(Vsb($M,Bv(tv(Kz,1),uyb,32,0,[ZM,pN,rN])))}
function q$(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C;u=new GU;for(m=new Tob(a.c);m.a<m.c.c.length;){l=Wv(Rob(m),16);for(p=new Tob(l.a);p.a<p.c.c.length;){n=Wv(Rob(p),9);if(n.g!=(CX(),xX)){continue}if(rJ(n,(Rib(),gib))==null){continue}q=null;s=null;r=null;for(A=new Tob(n.f);A.a<A.c.c.length;){w=Wv(Rob(A),7);switch(w.g.e){case 4:q=w;break;case 2:s=w;break;default:r=w;}}t=Wv(yU(r.e,0),12);i=new kJ(t.a);h=new II(r.i);vI(h,n.i);j=WI(i,0);$ub(j,h);v=lJ(t.a);k=new II(r.i);vI(k,n.i);TI(v,k,v.c.b,v.c);B=Wv(rJ(n,gib),9);C=Wv(yU(B.f,0),7);g=Wv(FU(q.b,xv(dB,gAb,12,0,0,1)),47);for(d=0,f=g.length;d<f;++d){b=g[d];eW(b,C);gJ(b.a,b.a.b,i)}g=Wv(FU(s.e,xv(dB,gAb,12,s.e.c.length,0,1)),47);for(c=0,e=g.length;c<e;++c){b=g[c];dW(b,C);gJ(b.a,0,v)}dW(t,null);eW(t,null);u.c[u.c.length]=n}}for(o=new Tob(u);o.a<o.c.c.length;){n=Wv(Rob(o),9);rX(n,null)}}
function _tb(){function e(){this.obj=this.createObject()}
;e.prototype.createObject=function(a){return Object.create(null)};e.prototype.get=function(a){return this.obj[a]};e.prototype.set=function(a,b){this.obj[a]=b};e.prototype[$Ab]=function(a){delete this.obj[a]};e.prototype.keys=function(){return Object.getOwnPropertyNames(this.obj)};e.prototype.entries=function(){var b=this.keys();var c=this;var d=0;return {'next':function(){if(d>=b.length)return {'done':true};var a=b[d++];return {'value':[a,c.get(a)],'done':false}}}};if(!Ztb()){e.prototype.createObject=function(){return {}};e.prototype.get=function(a){return this.obj[':'+a]};e.prototype.set=function(a,b){this.obj[':'+a]=b};e.prototype[$Ab]=function(a){delete this.obj[':'+a]};e.prototype.keys=function(){var a=[];for(var b in this.obj){b.charCodeAt(0)==58&&a.push(b.substring(1))}return a}}return e}
function fQ(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;k=new kW;sJ(k,PP,b);Umb(a.e,b,k);sJ(k,(Rib(),zib),c);!!a.d&&iQ(a.d,k,false);hQ(b,k);if(Lzb in b.a){q=k.a;r=Wv(Pu(b,Lzb),69);p=Wv(Pu(r,'left'),104);!!p&&(q.b=p.a);t=Wv(Pu(r,'top'),104);!!t&&(q.d=t.a);s=Wv(Pu(r,'right'),104);!!s&&(q.c=s.a);e=Wv(Pu(r,Azb),104);!!e&&(q.a=e.a)}l=(d=Wv(Hkb(mF),11),new atb(d,Wv(exb(d,d.length),11),0));sJ(k,jib,l);a.g==null&&(a.g=Xv(rJ(k,(zQ(),yQ))));if(Mzb in b.a){u=Pu(b,Mzb);if(!u.hc()){throw new GQ("The 'children' property of nodes must be an array.",u,b)}j=u.hc();if(j.a.length>0){!!c&&sJ(c,sib,k);h=xv(qB,Nzb,9,j.a.length,0,1);for(n=0;n<j.a.length;++n){i=gu(j,n);if(!i.kc()){throw new GQ("A 'children' array contains a non-object node element.",i,b)}f=eQ(a,i.kc(),k);h[n]=f}for(m=0;m<j.a.length;++m){o=gu(j,m).kc();g=h[m];Mzb in o.a&&!Ckb(Ixb(Xv(rJ(g,(eM(),KL)))))&&fQ(a,o,g)}}}return k}
function LO(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;if(!Qob(new Tob(AW(a.e)))){return}for(h=new Tob(AW(a.e));h.a<h.c.c.length;){g=Wv(Rob(h),161);j=Wv(g.e,7).g.e;++a.o[j];switch(Wv(g.e,7).g.e){case 4:case 2:a.n[j]+=g.e.j.b+(b?(d=Wv(g.e,7).d,new EP(d.d,d.b,d.a,d.c)).a+(e=Wv(g.e,7).d,new EP(e.d,e.b,e.a,e.c)).d:0);break;case 1:case 3:a.n[j]+=g.e.j.a+(b?(f=Wv(g.e,7).d,new EP(f.d,f.b,f.a,f.c)).b+(c=Wv(g.e,7).d,new EP(c.d,c.b,c.a,c.c)).c:0);}}i=Wv(oW(a.e,(eM(),NL)),100);i=i==(zM(),yM)?xM:i;a.g[1]=Wv(oW(a.e,PL),100);a.g[3]=Wv(oW(a.e,QL),100);a.g[4]=Wv(oW(a.e,RL),100);a.g[2]=Wv(oW(a.e,OL),100);for(l=(sN(),Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN])),n=0,p=l.length;n<p;++n){j=l[n];a.g[j.e]=a.g[j.e]==yM?i:a.g[j.e]}a.b=oW(a.e,jL)!=null;for(k=Bv(tv(Kz,1),uyb,32,0,[qN,$M,ZM,pN,rN]),m=0,o=k.length;m<o;++m){j=k[m];a.o[j.e]==1?(a.i[j.e]=2):!a.b&&a.g[j.e]==xM?(a.i[j.e]=a.o[j.e]+1):(a.i[j.e]=a.o[j.e]-1)}}
function Tfb(a,b,c,d,e,f){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;i=Wv(a.a,16);p=Wv(a.b,16);j=Wv(b.a,18);q=Wv(b.b,18);if(i){for(l=new Tob(i.a);l.a<l.c.c.length;){k=Wv(Rob(l),9);for(t=nX(k,(sN(),ZM)).mb();t.G();){s=Wv(t.H(),7);j.ib(s);for(h=new Tob(s.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);if(bW(g)){continue}c.c[c.c.length]=g;Ufb(g,d);r=g.c.f.g;(r==(CX(),AX)||r==BX)&&(e.c[e.c.length]=g,true);v=g.d;u=v.f.d;u==p?q.ib(v):u==i?j.ib(v):BU(c,g)}}}}if(p){for(l=new Tob(p.a);l.a<l.c.c.length;){k=Wv(Rob(l),9);for(o=new Tob(k.f);o.a<o.c.c.length;){n=Wv(Rob(o),7);for(h=new Tob(n.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);bW(g)&&(m=f.a.db(g,f),m==null)}}for(t=nX(k,(sN(),rN)).mb();t.G();){s=Wv(t.H(),7);q.ib(s);for(h=new Tob(s.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);if(bW(g)){continue}c.c[c.c.length]=g;Ufb(g,d);r=g.c.f.g;(r==(CX(),AX)||r==BX)&&(e.c[e.c.length]=g,true);v=g.d;u=v.f.d;u==p?q.ib(v):u==i?j.ib(v):BU(c,g)}}}}}
function acb(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B;t=b.c.length;e=new Cbb(a.b,c,null,null);B=xv(kw,hyb,26,t,12,1);p=xv(kw,hyb,26,t,12,1);o=xv(kw,hyb,26,t,12,1);q=0;for(h=0;h<t;h++){p[h]=$xb;o[h]=eyb}for(i=0;i<t;i++){d=(Cxb(i,b.c.length),Wv(b.c[i],81));B[i]=Abb(d);B[q]>B[i]&&(q=i);for(l=new Tob(a.b.c);l.a<l.c.c.length;){k=Wv(Rob(l),16);for(s=new Tob(k.a);s.a<s.c.c.length;){r=Wv(Rob(s),9);w=Ixb(d.n[r.k])+Ixb(d.d[r.k]);p[i]=p[i]<w?p[i]:w;o[i]=Nlb(o[i],w+r.j.b)}}}A=xv(kw,hyb,26,t,12,1);for(j=0;j<t;j++){(Cxb(j,b.c.length),Wv(b.c[j],81)).k==(Lbb(),Jbb)?(A[j]=p[q]-p[j]):(A[j]=o[q]-o[j])}f=xv(kw,hyb,26,t,12,1);for(n=new Tob(a.b.c);n.a<n.c.c.length;){m=Wv(Rob(n),16);for(v=new Tob(m.a);v.a<v.c.c.length;){u=Wv(Rob(v),9);for(g=0;g<t;g++){f[g]=Ixb((Cxb(g,b.c.length),Wv(b.c[g],81)).n[u.k])+Ixb((Cxb(g,b.c.length),Wv(b.c[g],81)).d[u.k])+A[g]}kpb(f);e.n[u.k]=(f[1]+f[2])/2;e.d[u.k]=0}}return e}
function Sfb(a,b,c,d,e,f){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;p=null;c==(fgb(),dgb)?(p=a):c==egb&&(p=b);for(r=(m=(new Snb(p.a)).a.bb().mb(),new Ynb(m));r.a.G();){q=(k=Wv(r.a.H(),21),Wv(k.yb(),7));s=MI(Bv(tv(qz,1),Fzb,10,0,[q.f.i,q.i,q.a])).b;v=new vtb;g=new vtb;for(i=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[q.b,q.e]))))));Cm(i);){h=Wv(Dm(i),12);if(Ckb(Ixb(Xv(rJ(h,(Rib(),Iib)))))!=d){continue}if(zU(e,h,0)!=-1){h.d==q?(t=h.c):(t=h.d);u=MI(Bv(tv(qz,1),Fzb,10,0,[t.f.i,t.i,t.a])).b;if((u-s<=0?0-(u-s):u-s)<0.2){continue}u<s?a.a.R(t)?stb(v,new RJ(dgb,h)):stb(v,new RJ(egb,h)):a.a.R(t)?stb(g,new RJ(dgb,h)):stb(g,new RJ(egb,h))}}if(v.a.Y()>1){vU(f,new mgb(q,v,c));for(o=(l=(new Snb(v.a)).a.bb().mb(),new Ynb(l));o.a.G();){n=(j=Wv(o.a.H(),21),Wv(j.yb(),27));BU(e,n.b)}}if(g.a.Y()>1){vU(f,new mgb(q,g,c));for(o=(l=(new Snb(g.a)).a.bb().mb(),new Ynb(l));o.a.G();){n=(j=Wv(o.a.H(),21),Wv(j.yb(),27));BU(e,n.b)}}}}
function dab(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A;e=0;s=0;r=(mp(),new ntb);d=new ntb;f=new ntb;A=new ntb;fab(a,f,A);b=null;q=0;w=0;t=true;i=true;for(m=0,o=a.length;m<o;++m){k=a[m];for(v=new Tob(k.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);switch(u.g.e){case 2:e+=cab(u,f);break;case 4:e+=cab(u,A);}}p=k.g;if(i&&(p==(CX(),AX)||p==BX)){j=Wv(rJ(k,(Rib(),nib)),9);if(!j){i=false;continue}if(b!=j){!!b&&Umb(r,b,new RJ(Elb(q),Elb(w)));b=j;q=0;w=0;t=true}k==b&&(t=false);if(t){q+=Wv(rJ(k,aib),24).a;Umb(d,k,Elb(q))}else{w+=Wv(rJ(k,aib),24).a;Umb(d,k,Elb(w))}}}!!b&&Umb(r,b,new RJ(Elb(q),Elb(w)));if(i){h=null;g=0;c=0;t=true;for(l=0,n=a.length;l<n;++l){k=a[l];p=k.g;switch(p.e){case 0:g=Wv(re(Ktb(d.d,k)),24).a;c=Wv(Wv(re(Ktb(r.d,k)),27).b,24).a;h=k;t=false;break;case 3:g=Wv(re(Ktb(d.d,k)),24).a;j=Wv(rJ(k,(Rib(),nib)),9);if(j!=h){c=Wv(Wv(re(Ktb(r.d,j)),27).a,24).a;h=j;t=true}break;default:s+=t?g:c-g;}}}return e+s}
function S4(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;l=(mp(),new ntb);j=new xk;for(d=new Tob(a.a.a.b);d.a<d.c.c.length;){b=Wv(Rob(d),25);if(aw(b,93)){k=Wv(b,93).b;Ltb(l.d,k,b)}else if(aw(b,82)){for(f=(o=(new Snb(Wv(b,82).d.a)).a.bb().mb(),new Ynb(o));f.a.G();){e=(g=Wv(f.a.H(),21),Wv(g.yb(),12));Fd(j,e,b)}}}for(c=new Tob(a.a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);if(aw(b,93)){k=Wv(b,93).b;for(i=Uh(mX(k));Cm(i);){h=Wv(Dm(i),12);if(bW(h)){continue}q=h.c;t=h.d;if((sN(),jN).kb(h.c.g)&&jN.kb(h.d.g)){continue}r=Wv(Smb(l,h.d.f),25);f7(i7(h7(j7(g7(new k7,0),100),a.c[b.f.d]),a.c[r.f.d]));if(q.g==rN&&TX((LX(),IX,q))){for(n=Wv(Dd(j,h),18).mb();n.G();){m=Wv(n.H(),25);if(m.j.d<b.j.d){p=a.c[m.f.d];s=a.c[b.f.d];if(p==s){continue}f7(i7(h7(j7(g7(new k7,1),100),p),s))}}}if(t.g==ZM&&WX((LX(),GX,t))){for(n=Wv(Dd(j,h),18).mb();n.G();){m=Wv(n.H(),25);if(m.j.d>b.j.d){p=a.c[b.f.d];s=a.c[m.f.d];if(p==s){continue}f7(i7(h7(j7(g7(new k7,1),100),p),s))}}}}}}}
function t3(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;g=new z3(a);h=Ao(pl(b,g));Gpb(h,new C3);e=a.b;switch(e.c){case 2:i=new E3(e.a);c=Al(pl(h,i));od(c)?(j=Wv(pd(c),91).b):(j=15);i=new E3(Jeb(e));c=Al(pl(h,i));od(c)?(f=Wv(pd(c),91).b):(f=15);i=new E3(e.b);c=Al(pl(h,i));od(c)?(k=Wv(pd(c),91).b):(k=15);d=p3(a,j,f,k);stb(b,new w3(d,a.c,a.e,a.a.c.f,e.a));stb(b,new w3(d,a.c,a.e,a.a.c.f,Jeb(e)));stb(b,new w3(d,a.c,a.e,a.a.c.f,e.b));break;case 1:i=new E3(e.a);c=Al(pl(h,i));od(c)?(j=Wv(pd(c),91).b):(j=15);i=new E3(e.b);c=Al(pl(h,i));od(c)?(k=Wv(pd(c),91).b):(k=15);d=q3(a,j,k);stb(b,new w3(d,a.c,a.e,a.a.c.f,e.a));stb(b,new w3(d,a.c,a.e,a.a.c.f,e.b));break;case 0:i=new E3(e.a);c=Al(pl(h,i));od(c)?(j=Wv(pd(c),91).b):(j=15);d=(l=a.b,m=xfb(a.a.c,a.a.d,j),Ue(a.a.a,Veb(m)),n=s3(a.a.b,m.a,l),o=new Dfb((!m.k&&(m.k=new Efb(Xeb(m))),m.k)),zfb(o),!n?o:Gfb(o,n));stb(b,new w3(d,a.c,a.e,a.a.c.f,e.a));break;default:throw new slb('The loopside must be defined.');}return d}
function Pbb(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;for(h=new Tob(a.a.c);h.a<h.c.c.length;){f=Wv(Rob(h),16);for(t=new Tob(f.a);t.a<t.c.c.length;){s=Wv(Rob(t),9);b.f[s.k]=s;b.a[s.k]=s;b.d[s.k]=0}}i=a.a.c;b.c==(Gbb(),Ebb)&&(i=aw(i,87)?Ii(Wv(i,87)):aw(i,88)?Wv(i,88).a:aw(i,63)?new ap(i):new Ro(i));for(g=i.mb();g.G();){f=Wv(g.H(),16);n=-1;m=f.a;if(b.k==(Lbb(),Kbb)){n=$xb;m=aw(m,87)?Ii(Wv(m,87)):aw(m,88)?Wv(m,88).a:aw(m,63)?new ap(m):new Ro(m)}for(v=m.mb();v.G();){u=Wv(v.H(),9);b.c==Ebb?(l=Wv(yU(a.b.f,u.k),20)):(l=Wv(yU(a.b.b,u.k),20));if(l.Y()>0){d=l.Y();j=hw(Math.floor((d+1)/2))-1;e=hw(Math.ceil((d+1)/2))-1;if(b.k==Kbb){for(k=e;k>=j;k--){if(b.a[u.k]==u){p=Wv(l.sb(k),27);o=Wv(p.a,9);if(!ttb(c,p.b)&&n>a.b.e[o.k]){b.a[o.k]=u;b.f[u.k]=b.f[o.k];b.a[u.k]=b.f[u.k];n=a.b.e[o.k]}}}}else{for(k=j;k<=e;k++){if(b.a[u.k]==u){r=Wv(l.sb(k),27);q=Wv(r.a,9);if(!ttb(c,r.b)&&n<a.b.e[q.k]){b.a[q.k]=u;b.f[u.k]=b.f[q.k];b.a[u.k]=b.f[u.k];n=a.b.e[q.k]}}}}}}}}
function Ieb(){Ieb=iI;meb=new Peb('N',0,(sN(),$M),$M,0);jeb=new Peb('EN',1,ZM,$M,1);ieb=new Peb('E',2,ZM,ZM,0);peb=new Peb('SE',3,pN,ZM,1);oeb=new Peb('S',4,pN,pN,0);Heb=new Peb('WS',5,rN,pN,1);Geb=new Peb('W',6,rN,rN,0);neb=new Peb('NW',7,$M,rN,1);keb=new Peb('ENW',8,ZM,rN,2);leb=new Peb('ESW',9,ZM,rN,2);qeb=new Peb('SEN',10,pN,$M,2);Eeb=new Peb('SWN',11,pN,$M,2);Feb=new Peb(szb,12,qN,qN,3);feb=bk(meb,jeb,ieb,peb,oeb,Heb,Bv(tv(_E,1),uyb,60,0,[Geb,neb,keb,leb,qeb,Eeb]));heb=(hi(),Zj(Bv(tv(UF,1),syb,1,4,[meb,ieb,oeb,Geb])));geb=Zj(Bv(tv(UF,1),syb,1,4,[jeb,peb,Heb,neb]));veb=new Gr($M);seb=Zj(Bv(tv(UF,1),syb,1,4,[ZM,$M]));reb=new Gr(ZM);yeb=Zj(Bv(tv(UF,1),syb,1,4,[pN,ZM]));xeb=new Gr(pN);Deb=Zj(Bv(tv(UF,1),syb,1,4,[rN,pN]));Ceb=new Gr(rN);web=Zj(Bv(tv(UF,1),syb,1,4,[$M,rN]));teb=Zj(Bv(tv(UF,1),syb,1,4,[ZM,$M,rN]));ueb=Zj(Bv(tv(UF,1),syb,1,4,[ZM,pN,rN]));Aeb=Zj(Bv(tv(UF,1),syb,1,4,[pN,rN,$M]));zeb=Zj(Bv(tv(UF,1),syb,1,4,[pN,ZM,$M]));Beb=(kr(),jr)}
function JZ(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;s=0;if(b.e.a==0){for(q=new Tob(a);q.a<q.c.c.length;){o=Wv(Rob(q),9);s=Nlb(s,o.i.a+o.j.a+o.e.c)}}else{s=b.e.a-b.d.a}s-=b.d.a;for(p=new Tob(a);p.a<p.c.c.length;){o=Wv(Rob(p),9);IZ(o.i,s-o.j.a);GZ(o);switch(Wv(rJ(o,(eM(),lL)),103).e){case 1:sJ(o,lL,(iK(),gK));break;case 2:sJ(o,lL,(iK(),fK));}r=o.j;for(u=new Tob(o.f);u.a<u.c.c.length;){t=Wv(Rob(u),7);IZ(t.i,r.a-t.j.a);IZ(t.a,t.j.a);QX(t,CZ(t.g));g=Wv(rJ(t,UL),24);!!g&&sJ(t,UL,Elb(-g.a));for(f=new Tob(t.e);f.a<f.c.c.length;){e=Wv(Rob(f),12);for(d=WI(e.a,0);d.b!=d.d.c;){c=Wv(_ub(d),10);c.a=s-c.a}j=Wv(rJ(e,CL),44);if(j){for(i=WI(j,0);i.b!=i.d.c;){h=Wv(_ub(i),10);h.a=s-h.a}}for(m=new Tob(e.b);m.a<m.c.c.length;){k=Wv(Rob(m),33);IZ(k.i,s-k.j.a)}}for(n=new Tob(t.c);n.a<n.c.c.length;){k=Wv(Rob(n),33);IZ(k.i,-k.j.a)}}if(o.g==(CX(),xX)){sJ(o,(Rib(),hib),CZ(Wv(rJ(o,hib),32)));FZ(o)}for(l=new Tob(o.c);l.a<l.c.c.length;){k=Wv(Rob(l),33);IZ(k.i,r.a-k.j.a)}}}
function LZ(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;s=0;if(b.e.b==0){for(q=new Tob(a);q.a<q.c.c.length;){o=Wv(Rob(q),9);s=Nlb(s,o.i.b+o.j.b+o.e.a)}}else{s=b.e.b-b.d.b}s-=b.d.b;for(p=new Tob(a);p.a<p.c.c.length;){o=Wv(Rob(p),9);KZ(o.i,s-o.j.b);HZ(o);switch(Wv(rJ(o,(eM(),lL)),103).e){case 3:sJ(o,lL,(iK(),dK));break;case 4:sJ(o,lL,(iK(),hK));}r=o.j;for(u=new Tob(o.f);u.a<u.c.c.length;){t=Wv(Rob(u),7);KZ(t.i,r.b-t.j.b);KZ(t.a,t.j.b);QX(t,DZ(t.g));g=Wv(rJ(t,UL),24);!!g&&sJ(t,UL,Elb(-g.a));for(f=new Tob(t.e);f.a<f.c.c.length;){e=Wv(Rob(f),12);for(d=WI(e.a,0);d.b!=d.d.c;){c=Wv(_ub(d),10);c.b=s-c.b}j=Wv(rJ(e,CL),44);if(j){for(i=WI(j,0);i.b!=i.d.c;){h=Wv(_ub(i),10);h.b=s-h.b}}for(m=new Tob(e.b);m.a<m.c.c.length;){k=Wv(Rob(m),33);KZ(k.i,s-k.j.b)}}for(n=new Tob(t.c);n.a<n.c.c.length;){k=Wv(Rob(n),33);KZ(k.i,-k.j.b)}}if(o.g==(CX(),xX)){sJ(o,(Rib(),hib),DZ(Wv(rJ(o,hib),32)));EZ(o)}for(l=new Tob(o.c);l.a<l.c.c.length;){k=Wv(Rob(l),33);KZ(k.i,r.b-k.j.b)}}}
function qP(a,b,c){var d,e,f,g,h,i,j,k,l,m,n;d=new VN(b.e.i.a,b.e.i.b,b.e.j.a,b.e.j.b);e=new UN;if(a.c){for(g=new Tob(zW(b));g.a<g.c.c.length;){f=Wv(Rob(g),129);e.d=f.e.i.a+b.e.i.a;e.e=f.e.i.b+b.e.i.b;e.c=f.e.j.a;e.b=f.e.j.b;TN(d,e)}}for(k=new Tob(AW(b));k.a<k.c.c.length;){j=Wv(Rob(k),161);l=j.e.i.a+b.e.i.a;m=j.e.i.b+b.e.i.b;if(a.e){e.d=l;e.e=m;e.c=j.e.j.a;e.b=j.e.j.b;TN(d,e)}if(a.d){for(g=new Tob(DW(j));g.a<g.c.c.length;){f=Wv(Rob(g),129);e.d=f.e.i.a+l;e.e=f.e.i.b+m;e.c=f.e.j.a;e.b=f.e.j.b;TN(d,e)}}if(a.b){n=new HI(-c,-c);if(gw(oW(b,(eM(),VL)))===gw((UM(),TM))){for(g=new Tob(DW(j));g.a<g.c.c.length;){f=Wv(Rob(g),129);n.a+=f.e.j.a+c;n.b+=f.e.j.b+c}}n.a=Nlb(n.a,0);n.b=Nlb(n.b,0);pP(d,EW(j),CW(j),b,j,n,c)}}a.b&&pP(d,(ypb(),ypb(),vpb),(null,vpb),b,null,null,c);i=new FP((h=Wv(b.e,9).e,new EP(h.d,h.b,h.a,h.c)));i.d=b.e.i.b-d.e;i.a=d.e+d.b-(b.e.i.b+b.e.j.b);i.b=b.e.i.a-d.d;i.c=d.d+d.c-(b.e.i.a+b.e.j.a);Wv(b.e,9).e.b=i.b;Wv(b.e,9).e.d=i.d;Wv(b.e,9).e.c=i.c;Wv(b.e,9).e.a=i.a}
function XT(){XT=iI;WT=new xk;Fd(WT,(sN(),dN),hN);Fd(WT,oN,kN);Fd(WT,oN,hN);Fd(WT,_M,gN);Fd(WT,_M,hN);Fd(WT,eN,iN);Fd(WT,eN,hN);Fd(WT,mN,bN);Fd(WT,mN,hN);Fd(WT,jN,cN);Fd(WT,jN,iN);Fd(WT,jN,bN);Fd(WT,jN,hN);Fd(WT,cN,jN);Fd(WT,cN,kN);Fd(WT,cN,gN);Fd(WT,cN,hN);Fd(WT,lN,lN);Fd(WT,lN,iN);Fd(WT,lN,kN);Fd(WT,fN,fN);Fd(WT,fN,iN);Fd(WT,fN,gN);Fd(WT,nN,nN);Fd(WT,nN,bN);Fd(WT,nN,kN);Fd(WT,aN,aN);Fd(WT,aN,bN);Fd(WT,aN,gN);Fd(WT,iN,eN);Fd(WT,iN,jN);Fd(WT,iN,lN);Fd(WT,iN,fN);Fd(WT,iN,iN);Fd(WT,iN,kN);Fd(WT,iN,gN);Fd(WT,iN,hN);Fd(WT,bN,mN);Fd(WT,bN,jN);Fd(WT,bN,nN);Fd(WT,bN,aN);Fd(WT,bN,bN);Fd(WT,bN,kN);Fd(WT,bN,gN);Fd(WT,bN,hN);Fd(WT,kN,oN);Fd(WT,kN,cN);Fd(WT,kN,lN);Fd(WT,kN,nN);Fd(WT,kN,iN);Fd(WT,kN,bN);Fd(WT,kN,kN);Fd(WT,kN,hN);Fd(WT,gN,_M);Fd(WT,gN,cN);Fd(WT,gN,fN);Fd(WT,gN,aN);Fd(WT,gN,iN);Fd(WT,gN,bN);Fd(WT,gN,gN);Fd(WT,gN,hN);Fd(WT,hN,dN);Fd(WT,hN,oN);Fd(WT,hN,_M);Fd(WT,hN,eN);Fd(WT,hN,mN);Fd(WT,hN,jN);Fd(WT,hN,cN);Fd(WT,hN,iN);Fd(WT,hN,bN);Fd(WT,hN,kN);Fd(WT,hN,gN);Fd(WT,hN,hN)}
function Tbb(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;if(c.n[b.k]!=null){return}i=true;c.n[b.k]=0;g=b;r=c.k==(Lbb(),Jbb)?Vzb:Uzb;do{e=a.b.e[g.k];f=g.d.a.c.length;h=g.g;if(c.k==Jbb&&e>0||c.k==Kbb&&e<f-1){c.k==Kbb?(j=Wv(yU(g.d.a,e+1),9)):(j=Wv(yU(g.d.a,e-1),9));l=c.f[j.k];k=j.g;Tbb(a,l,c);r=a.e.Ic(r,b,g);c.i[b.k]==b&&(c.i[b.k]=c.i[l.k]);if(c.i[b.k]==c.i[l.k]){q=Wjb(a.d,h,k);if(c.k==Kbb){d=Ixb(c.n[b.k]);n=Ixb(c.n[l.k])+Ixb(c.d[j.k])-j.e.d-q-g.e.a-g.j.b-Ixb(c.d[g.k]);if(i){i=false;c.n[b.k]=n<r?n:r}else{c.n[b.k]=d<(n<r?n:r)?d:n<r?n:r}}else{d=Ixb(c.n[b.k]);n=Ixb(c.n[l.k])+Ixb(c.d[j.k])+j.j.b+j.e.a+q+g.e.d-Ixb(c.d[g.k]);if(i){i=false;c.n[b.k]=n>r?n:r}else{c.n[b.k]=d>(n>r?n:r)?d:n>r?n:r}}}else{q=a.d.f;p=Rbb(a,c.i[b.k]);m=Rbb(a,c.i[l.k]);if(c.k==Kbb){o=Ixb(c.n[b.k])+Ixb(c.d[g.k])+g.j.b+g.e.a+q-(Ixb(c.n[l.k])+Ixb(c.d[j.k])-j.e.d);Xbb(p,m,o)}else{o=Ixb(c.n[b.k])+Ixb(c.d[g.k])-g.e.d-Ixb(c.n[l.k])-Ixb(c.d[j.k])-j.j.b-j.e.a-q;Xbb(p,m,o)}}}else{r=a.e.Ic(r,b,g)}g=c.a[g.k]}while(g!=b);ycb(a.e,b)}
function sZ(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;m=false;l=false;if(MM(Wv(rJ(d,(eM(),TL)),28))){g=false;h=false;t:for(o=new Tob(d.f);o.a<o.c.c.length;){n=Wv(Rob(o),7);for(q=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[new fY(n),new lY(n)]))))));Cm(q);){p=Wv(Dm(q),7);if(!Ckb(Ixb(Xv(rJ(p.f,qL))))){if(n.g==(sN(),$M)){g=true;break t}if(n.g==pN){h=true;break t}}}}m=h&&!g;l=g&&!h}if(!m&&!l&&d.c.c.length!=0){k=0;for(j=new Tob(d.c);j.a<j.c.c.length;){i=Wv(Rob(j),33);k+=i.i.b+i.j.b/2}k/=d.c.c.length;s=k>=d.j.b/2}else{s=!l}if(s){r=Wv(rJ(d,(Rib(),Qib)),20);if(!r){f=new GU;sJ(d,Qib,f)}else if(m){f=r}else{e=Wv(rJ(d,Yhb),20);if(!e){f=new GU;sJ(d,Yhb,f)}else{r.Y()<=e.Y()?(f=r):(f=e)}}}else{e=Wv(rJ(d,(Rib(),Yhb)),20);if(!e){f=new GU;sJ(d,Yhb,f)}else if(l){f=e}else{r=Wv(rJ(d,Qib),20);if(!r){f=new GU;sJ(d,Qib,f)}else{e.Y()<=r.Y()?(f=e):(f=r)}}}f.ib(a);sJ(a,(Rib(),Zhb),c);if(b.d==c){eW(b,null);c.b.c.length+c.e.c.length==0&&PX(c,null)}else{dW(b,null);c.b.c.length+c.e.c.length==0&&PX(c,null)}_I(b.a)}
function rU(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;c=new bV(b);c.a||kU(b);j=jU(b);i=new xk;q=new oV;for(p=new Tob(b.b);p.a<p.c.c.length;){o=Wv(Rob(p),9);for(e=Uh(mX(o));Cm(e);){d=Wv(Dm(e),12);if(d.c.f.g==(CX(),xX)||d.d.f.g==xX){k=qU(a,d,j,q);Fd(i,oU(k.d),k.a)}}}g=new GU;for(t=Wv(rJ(c.c,(Rib(),fib)),18).mb();t.G();){s=Wv(t.H(),32);n=q.c[s.e];m=q.b[s.e];h=q.a[s.e];f=null;r=null;switch(s.e){case 4:f=new VN(a.d.a,n,j.b.a-a.d.a,m-n);r=new VN(a.d.a,n,h,m-n);YU(j,new HI(f.d+f.c,f.e));YU(j,new HI(f.d+f.c,f.e+f.b));break;case 2:f=new VN(j.a.a,n,a.c.a-j.a.a,m-n);r=new VN(a.c.a-h,n,h,m-n);YU(j,new HI(f.d,f.e));YU(j,new HI(f.d,f.e+f.b));break;case 1:f=new VN(n,a.d.b,m-n,j.b.b-a.d.b);r=new VN(n,a.d.b,m-n,h);YU(j,new HI(f.d,f.e+f.b));YU(j,new HI(f.d+f.c,f.e+f.b));break;case 3:f=new VN(n,j.a.b,m-n,a.c.b-j.a.b);r=new VN(n,a.c.b-h,m-n,h);YU(j,new HI(f.d,f.e));YU(j,new HI(f.d+f.c,f.e));}if(f){l=new jV;l.d=s;l.b=f;l.c=r;l.a=pr(Wv(Dd(i,oU(s)),18));g.c[g.c.length]=l}}xU(c.b,g);c.d=pT(tT(j));return c}
function tt(){var a=['\\u0000','\\u0001','\\u0002','\\u0003','\\u0004','\\u0005','\\u0006','\\u0007','\\b','\\t','\\n','\\u000B','\\f','\\r','\\u000E','\\u000F','\\u0010','\\u0011','\\u0012','\\u0013','\\u0014','\\u0015','\\u0016','\\u0017','\\u0018','\\u0019','\\u001A','\\u001B','\\u001C','\\u001D','\\u001E','\\u001F'];a[34]='\\"';a[92]='\\\\';a[173]='\\u00ad';a[1536]='\\u0600';a[1537]='\\u0601';a[1538]='\\u0602';a[1539]='\\u0603';a[1757]='\\u06dd';a[1807]='\\u070f';a[6068]='\\u17b4';a[6069]='\\u17b5';a[8203]='\\u200b';a[8204]='\\u200c';a[8205]='\\u200d';a[8206]='\\u200e';a[8207]='\\u200f';a[8232]='\\u2028';a[8233]='\\u2029';a[8234]='\\u202a';a[8235]='\\u202b';a[8236]='\\u202c';a[8237]='\\u202d';a[8238]='\\u202e';a[8288]='\\u2060';a[8289]='\\u2061';a[8290]='\\u2062';a[8291]='\\u2063';a[8292]='\\u2064';a[8298]='\\u206a';a[8299]='\\u206b';a[8300]='\\u206c';a[8301]='\\u206d';a[8302]='\\u206e';a[8303]='\\u206f';a[65279]='\\ufeff';a[65529]='\\ufff9';a[65530]='\\ufffa';a[65531]='\\ufffb';return a}
function eab(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w;b=0;r=true;w=null;for(d=0;d<a.length;d++){f=a[d];q=f.g;if(q==(CX(),AX)){w=f;r=false}else if(q==BX){if(aw(rJ(f,(Rib(),uib)),12)){continue}c=Wv(rJ(f,uib),9);if(w!=c){w=c;r=true}if(!LM(Wv(rJ(c,(eM(),TL)),28))){continue}m=null;o=null;for(t=new Tob(f.f);t.a<t.c.c.length;){s=Wv(Rob(t),7);s.b.c.length==0?s.e.c.length==0||(o=Wv(rJ(s,uib),7)):(m=Wv(rJ(s,uib),7))}for(e=d+1;e<a.length;e++){g=a[e];l=g.g;if(l==AX){break}else if(l==BX){if(gw(rJ(g,uib))!==gw(c)){break}h=null;j=null;for(v=new Tob(g.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);u.b.c.length==0?u.e.c.length==0||(j=Wv(rJ(u,uib),7)):(h=Wv(rJ(u,uib),7))}if(r){n=false;p=false;if(!!o&&!!h&&o.k<h.k){++b;p=true}if(!!m&&!!j&&m.k>j.k){++b;n=true}if(!!o&&!!j&&o.k>j.k){++b;p=true}if(!!m&&!!h&&m.k<h.k){++b;n=true}n&&p&&m==o&&--b}else{i=false;k=false;if(!!m&&!!j&&m.k<j.k){++b;k=true}if(!!o&&!!h&&o.k>h.k){++b;i=true}if(!!m&&!!h&&m.k<h.k){++b;i=true}if(!!o&&!!j&&o.k>j.k){++b;k=true}i&&k&&h==j&&--b}}}}}return b}
function Oab(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D;for(t=a.a,u=0,v=t.length;u<v;++u){s=t[u];j=$xb;k=$xb;for(o=new Tob(s.f);o.a<o.c.c.length;){m=Wv(Rob(o),9);g=!m.d?-1:zU(m.d.a,m,0);if(g>0){l=Wv(yU(m.d.a,g-1),9);B=Xjb(a.b,m,l);q=m.i.b-m.e.d-(l.i.b+l.j.b+l.e.a+B)}else{q=m.i.b-m.e.d}j=q<j?q:j;if(g<m.d.a.c.length-1){l=Wv(yU(m.d.a,g+1),9);B=Xjb(a.b,m,l);r=l.i.b-l.e.d-(m.i.b+m.j.b+m.e.a+B)}else{r=2*m.i.b}k=r<k?r:k}i=$xb;f=false;e=Wv(yU(s.f,0),9);for(D=new Tob(e.f);D.a<D.c.c.length;){C=Wv(Rob(D),7);p=e.i.b+C.i.b+C.a.b;for(d=new Tob(C.b);d.a<d.c.c.length;){c=Wv(Rob(d),12);w=c.c;b=w.f.i.b+w.i.b+w.a.b-p;if((b<=0?0-b:b)<(i<=0?0-i:i)&&(b<=0?0-b:b)<(b<0?j:k)){i=b;f=true}}}h=Wv(yU(s.f,s.f.c.length-1),9);for(A=new Tob(h.f);A.a<A.c.c.length;){w=Wv(Rob(A),7);p=h.i.b+w.i.b+w.a.b;for(d=new Tob(w.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);C=c.d;b=C.f.i.b+C.i.b+C.a.b-p;if((b<=0?0-b:b)<(i<=0?0-i:i)&&(b<=0?0-b:b)<(b<0?j:k)){i=b;f=true}}}if(f&&i!=0){for(n=new Tob(s.f);n.a<n.c.c.length;){m=Wv(Rob(n),9);m.i.b+=i}}}}
function bU(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D;l=dU($T(a,(sN(),dN)),b);o=cU($T(a,eN),b);u=cU($T(a,mN),b);B=eU($T(a,oN),b);m=eU($T(a,_M),b);s=cU($T(a,lN),b);p=cU($T(a,fN),b);w=cU($T(a,nN),b);v=cU($T(a,aN),b);C=eU($T(a,cN),b);r=cU($T(a,jN),b);t=cU($T(a,iN),b);A=cU($T(a,bN),b);D=eU($T(a,kN),b);n=eU($T(a,gN),b);q=cU($T(a,hN),b);c=oJ(Bv(tv(kw,1),hyb,26,12,[s.a,B.a,w.a,D.a]));d=oJ(Bv(tv(kw,1),hyb,26,12,[o.a,l.a,u.a,q.a]));e=r.a;f=oJ(Bv(tv(kw,1),hyb,26,12,[p.a,m.a,v.a,n.a]));j=oJ(Bv(tv(kw,1),hyb,26,12,[s.b,o.b,p.b,t.b]));i=oJ(Bv(tv(kw,1),hyb,26,12,[B.b,l.b,m.b,q.b]));k=C.b;h=oJ(Bv(tv(kw,1),hyb,26,12,[w.b,u.b,v.b,A.b]));VT($T(a,dN),c+e,j+k);VT($T(a,hN),c+e,j+k);VT($T(a,eN),c+e,0);VT($T(a,mN),c+e,j+k+i);VT($T(a,oN),0,j+k);VT($T(a,_M),c+e+d,j+k);VT($T(a,fN),c+e+d,0);VT($T(a,nN),0,j+k+i);VT($T(a,aN),c+e+d,j+k+i);VT($T(a,cN),0,j);VT($T(a,jN),c,0);VT($T(a,bN),0,j+k+i);VT($T(a,gN),c+e+d,0);g=new FI;g.a=oJ(Bv(tv(kw,1),hyb,26,12,[c+d+e+f,C.a,t.a,A.a]));g.b=oJ(Bv(tv(kw,1),hyb,26,12,[j+i+k+h,r.b,D.b,n.b]));return g}
function Nfb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;d=new jJ;j=null;o=a.c;n=o.f.g;if(n!=(CX(),AX)&&n!=BX){throw new slb('The target node of the edge must be a normal node or a northSouthPort.')}if(n==BX){m=Wv(rJ(o,(Rib(),uib)),7);j=new HI(MI(Bv(tv(qz,1),Fzb,10,0,[m.f.i,m.i,m.a])).a,MI(Bv(tv(qz,1),Fzb,10,0,[o.f.i,o.i,o.a])).b);o=m}SI(d,MI(Bv(tv(qz,1),Fzb,10,0,[o.f.i,o.i,o.a])));g=Nlb(5,pgb(o.f,o.g));l=new GI(sgb(o.g));l.a*=g;l.b*=g;QI(d,vI(l,MI(Bv(tv(qz,1),Fzb,10,0,[o.f.i,o.i,o.a]))));!!j&&TI(d,j,d.c.b,d.c);f=a;i=a;h=null;c=false;while(f){e=f.a;if(e.b!=0){if(c){QI(d,CI(vI(h,(Bxb(e.b!=0),Wv(e.a.a.c,10))),0.5));c=false}else{c=true}h=xI((Bxb(e.b!=0),Wv(e.c.b.c,10)));Ue(d,e);_I(e)}i=f;f=Wv(re(Ktb(b.d,f)),12)}p=i.d;if(p.f.g==BX){m=Wv(rJ(p,(Rib(),uib)),7);QI(d,new HI(MI(Bv(tv(qz,1),Fzb,10,0,[m.f.i,m.i,m.a])).a,MI(Bv(tv(qz,1),Fzb,10,0,[p.f.i,p.i,p.a])).b));p=m}g=Nlb(5,pgb(p.f,p.g));l=new GI(sgb(p.g));CI(l,g);QI(d,vI(l,MI(Bv(tv(qz,1),Fzb,10,0,[p.f.i,p.i,p.a]))));SI(d,MI(Bv(tv(qz,1),Fzb,10,0,[p.f.i,p.i,p.a])));k=new efb(d);Ue(a.a,Veb(k))}
function bZ(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o;if(gw(rJ(a.c,(eM(),TL)))===gw((KM(),GM))||gw(rJ(a.c,TL))===gw(FM)){for(k=new Tob(a.c.f);k.a<k.c.c.length;){j=Wv(Rob(k),7);if(j.g==(sN(),$M)||j.g==pN){return false}}}for(d=Uh(mX(a.c));Cm(d);){c=Wv(Dm(d),12);if(c.c.f==c.d.f){return false}}if(MM(Wv(rJ(a.c,TL),28))){n=new GU;for(i=nX(a.c,(sN(),rN)).mb();i.G();){g=Wv(i.H(),7);vU(n,Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[g.b,g.e]))))))}o=(_b(n),new Vh(n));n=new GU;for(h=nX(a.c,ZM).mb();h.G();){g=Wv(h.H(),7);vU(n,Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[g.b,g.e]))))))}b=(_b(n),new Vh(n))}else{o=iX(a.c);b=mX(a.c)}f=!sl(mX(a.c));e=!sl(iX(a.c));if(!f&&!e){return false}if(!f){a.e=1;return true}if(!e){a.e=0;return true}if(Ul((Il(),new Im(Dl(ul(o.a,new yl)))))==1){l=(_b(o),Wv(Ql(new Im(Dl(ul(o.a,new yl)))),12)).c.f;if(l.g==(CX(),zX)&&Wv(rJ(l,(Rib(),qib)),7).f!=a.c){a.e=2;return true}}if(Ul(new Im(Dl(ul(b.a,new yl))))==1){m=(_b(b),Wv(Ql(new Im(Dl(ul(b.a,new yl)))),12)).d.f;if(m.g==(CX(),zX)&&Wv(rJ(m,(Rib(),rib)),7).f!=a.c){a.e=3;return true}}return false}
function K$(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;d=new GU;e=$xb;f=$xb;g=$xb;if(c){e=a.e.a;for(p=new Tob(b.f);p.a<p.c.c.length;){o=Wv(Rob(p),7);for(i=new Tob(o.e);i.a<i.c.c.length;){h=Wv(Rob(i),12);if(h.a.b!=0){k=Wv(UI(h.a),10);if(k.a<e){f=e-k.a;g=$xb;d.c=xv(UF,syb,1,0,4,1);e=k.a}if(k.a<=e){d.c[d.c.length]=h;h.a.b>1&&(g=Qlb(g,Jlb(Wv(tn(h.a,1),10).b-k.b)))}}}}}else{for(p=new Tob(b.f);p.a<p.c.c.length;){o=Wv(Rob(p),7);for(i=new Tob(o.b);i.a<i.c.c.length;){h=Wv(Rob(i),12);if(h.a.b!=0){m=Wv(VI(h.a),10);if(m.a>e){f=m.a-e;g=$xb;d.c=xv(UF,syb,1,0,4,1);e=m.a}if(m.a>=e){d.c[d.c.length]=h;h.a.b>1&&(g=Qlb(g,Jlb(Wv(tn(h.a,h.a.b-2),10).b-m.b)))}}}}}if(d.c.length!=0&&f>b.j.a/2&&g>b.j.b/2){n=new RX;PX(n,b);QX(n,(sN(),$M));n.i.a=b.j.a/2;r=new RX;PX(r,b);QX(r,pN);r.i.a=b.j.a/2;r.i.b=b.j.b;for(i=new Tob(d);i.a<i.c.c.length;){h=Wv(Rob(i),12);if(c){j=Wv(YI(h.a),10);q=h.a.b==0?MX(h.d):Wv(UI(h.a),10);q.b>=j.b?dW(h,r):dW(h,n)}else{j=Wv(ZI(h.a),10);q=h.a.b==0?MX(h.c):Wv(VI(h.a),10);q.b>=j.b?eW(h,r):eW(h,n)}l=Wv(rJ(h,(eM(),CL)),44);!!l&&Ve(l,j,true)}b.i.a=e-b.j.a/2}}
function N2(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;r=new GU;s=new GU;t=new GU;for(f=new Tob(b);f.a<f.c.c.length;){e=Wv(Rob(f),75);e.k>50?(r.c[r.c.length]=e,true):e.k>0?(s.c[s.c.length]=e,true):(t.c[t.c.length]=e,true)}if(s.c.length==1&&r.c.length==0){xU(r,s);s.c=xv(UF,syb,1,0,4,1)}r.c.length!=0&&Zsb(U2(a.a),(Ieb(),meb))&&Zsb(U2(a.a),(Ieb(),oeb))?L2(a,r):xU(s,r);s.c.length==0||M2(a,s);if(t.c.length!=0){c=V2(a.a);if(c.c!=0){k=new Tob(t);i=(_b(c),Nl((new vl(c)).a));while(k.a<k.c.c.length){e=Wv(Rob(k),75);while(k.a<k.c.c.length&&e.a.a.Y()<2){e=Wv(Rob(k),75)}if(e.a.a.Y()>1){p=Wv(nm(i),60);aeb(e,p,true);Sob(k);Y2(a.a,p)}}}m=t.c.length;d=O2(a);n=new GU;g=m/T2(a.a).c|0;for(h=0;h<g;h++){xU(n,T2(a.a))}o=m%T2(a.a).c;if(o>3){xU(n,(Ieb(),Ieb(),geb));o-=4}switch(o){case 3:vU(n,Meb(d));case 2:q=Leb(Meb(d));do{q=Leb(q)}while(!Zsb(U2(a.a),q));n.c[n.c.length]=q;q=Neb(Meb(d));do{q=Neb(q)}while(!Zsb(U2(a.a),q));n.c[n.c.length]=q;break;case 1:vU(n,Meb(d));}l=new Tob(n);j=new Tob(t);while(l.a<l.c.c.length&&j.a<j.c.c.length){aeb(Wv(Rob(j),75),Wv(Rob(l),60),true)}}}
function G9(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w;k=b.c.c.length;a.a=xv(qB,Txb,51,k,0,2);a.b=xv(qB,Txb,51,k,0,2);a.k=xv(qB,Txb,51,k,0,2);i=xv(mw,Yyb,26,k,12,1);g=xv(KH,xAb,26,k,13,1);a.c=xv(KH,xAb,26,k,13,1);a.d=xv(KH,xAb,26,k,13,1);r=0;v=0;m=new Fnb(b.c,0);while(m.b<m.d.Y()){j=(Bxb(m.b<m.d.Y()),Wv(m.d.sb(m.c=m.b++),16));l=m.b-1;n=j.a.c.length;a.a[l]=xv(qB,Nzb,9,n,0,1);a.k[l]=xv(qB,Nzb,9,n,0,1);a.b[l]=xv(qB,Nzb,9,n,0,1);i[l]=0;g[l]=false;s=new Fnb(j.a,0);while(s.b<s.d.Y()){q=(Bxb(s.b<s.d.Y()),Wv(s.d.sb(s.c=s.b++),9));a.b[l][s.b-1]=q;q.k=r++;o=Wv(rJ(q,(Rib(),nib)),9);!!o&&(Nm(a.g,o,q,null),true);for(u=new Tob(q.f);u.a<u.c.c.length;){t=Wv(Rob(u),7);t.k=v++;for(f=new Tob(t.e);f.a<f.c.c.length;){e=Wv(Rob(f),12);e.d.f.d==j&&++i[l]}t.g==(sN(),ZM)?t.e.c.length+t.b.c.length>1&&(a.c[l]=true):t.g==rN&&t.e.c.length+t.b.c.length>1&&(a.d[l]=true)}if(q.g==(CX(),BX)){++i[l];g[l]=true}}}c=true;p=true;for(h=0;h<a.d.length-1;h++){d=a.c[h]||a.d[h+1];c=c&d;p=p&!d}a.j=xv(lw,tAb,26,v,12,1);w=xv(mw,Yyb,26,v,12,1);if(!c){a.i=new iab(i,g,w);a.f=a.i}if(!p){a.e=new mab(i,g,w);a.f=a.e}}
function iU(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B;a.d=new HI(Uzb,Uzb);a.c=new HI(Vzb,Vzb);for(m=b.mb();m.G();){k=Wv(m.H(),55);for(t=new Tob(k.b);t.a<t.c.c.length;){s=Wv(Rob(t),9);a.d.a=Qlb(a.d.a,s.i.a-s.e.b);a.d.b=Qlb(a.d.b,s.i.b-s.e.d);a.c.a=Nlb(a.c.a,s.i.a+s.j.a+s.e.c);a.c.b=Nlb(a.c.b,s.i.b+s.j.b+s.e.a)}}h=new cV;for(l=b.mb();l.G();){k=Wv(l.H(),55);d=rU(a,k);vU(h.a,d);d.a=d.a|!Wv(rJ(d.c,(Rib(),fib)),18).V()}a.b=(xR(),B=new HR,B.f=new kR(c),B.b=jR(B.f,h),B);BR((o=a.b,new sI,o));a.e=new FI;a.a=a.b.f.e;for(g=new Tob(h.a);g.a<g.c.c.length;){e=Wv(Rob(g),347);u=CR(a.b,e);TW(e.c,u.a,u.b);for(q=new Tob(e.c.b);q.a<q.c.c.length;){p=Wv(Rob(q),9);if(p.g==(CX(),xX)){r=mU(a,p.i,Wv(rJ(p,(Rib(),hib)),32));vI(BI(p.i),r)}}}for(f=new Tob(h.a);f.a<f.c.c.length;){e=Wv(Rob(f),347);for(j=new Tob(aV(e));j.a<j.c.c.length;){i=Wv(Rob(j),12);A=new kJ(i.a);rn(A,0,MX(i.c));QI(A,MX(i.d));n=null;for(w=WI(A,0);w.b!=w.d.c;){v=Wv(_ub(w),10);if(!n){n=v;continue}if(Xs(n.a,v.a)){a.e.a=Qlb(a.e.a,n.a);a.a.a=Nlb(a.a.a,n.a)}else if(Xs(n.b,v.b)){a.e.b=Qlb(a.e.b,n.b);a.a.b=Nlb(a.a.b,n.b)}n=v}}}zI(a.e);vI(a.a,a.e)}
function U1(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F;p=new HU(b.b);u=new HU(b.b);m=new HU(b.b);B=new HU(b.b);q=new HU(b.b);for(A=WI(b,0);A.b!=A.d.c;){v=Wv(_ub(A),7);for(h=new Tob(v.e);h.a<h.c.c.length;){f=Wv(Rob(h),12);if(f.c.f==f.d.f){if(v.g==f.d.g){B.c[B.c.length]=f;continue}else if(v.g==(sN(),$M)&&f.d.g==pN){q.c[q.c.length]=f;continue}}}}for(i=new Tob(q);i.a<i.c.c.length;){f=Wv(Rob(i),12);V1(a,f,c,d,(sN(),ZM))}for(g=new Tob(B);g.a<g.c.c.length;){f=Wv(Rob(g),12);C=new uX(a);sX(C,(CX(),BX));sJ(C,(eM(),TL),(KM(),FM));sJ(C,(Rib(),uib),f);D=new RX;sJ(D,uib,f.d);QX(D,(sN(),rN));PX(D,C);F=new RX;sJ(F,uib,f.c);QX(F,ZM);PX(F,C);sJ(f.c,Bib,C);sJ(f.d,Bib,C);dW(f,null);eW(f,null);c.c[c.c.length]=C;sJ(C,aib,Elb(2))}for(w=WI(b,0);w.b!=w.d.c;){v=Wv(_ub(w),7);j=v.b.c.length>0;r=v.e.c.length>0;j&&r?(m.c[m.c.length]=v,true):j?(p.c[p.c.length]=v,true):r&&(u.c[u.c.length]=v,true)}for(o=new Tob(p);o.a<o.c.c.length;){n=Wv(Rob(o),7);vU(e,T1(a,n,null,c))}for(t=new Tob(u);t.a<t.c.c.length;){s=Wv(Rob(t),7);vU(e,T1(a,null,s,c))}for(l=new Tob(m);l.a<l.c.c.length;){k=Wv(Rob(l),7);vU(e,T1(a,k,k,c))}}
function ZP(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A;u=new II(b.d);i=new GU;for(t=new Tob(b.b);t.a<t.c.c.length;){r=Wv(Rob(t),9);n=Wv(Smb(a.j,r),69);if(n){$P(a,r,n,u);for(w=new Tob(r.f);w.a<w.c.c.length;){v=Wv(Rob(w),7);o=Wv(Smb(a.n,v),69);if(o){$P(a,v,o,QP);WP(o,(eM(),WL),new lv(yc(v.g)))}if(gw(rJ(r,(eM(),VL)))!==gw((UM(),RM))){for(q=new Tob(v.c);q.a<q.c.c.length;){p=Wv(Rob(q),33);m=Wv(Smb(a.f,p),69);$P(a,p,m,QP)}}}if(Wv(rJ(r,(eM(),JL)),86).Y()!=0){for(q=new Tob(r.c);q.a<q.c.c.length;){p=Wv(Rob(q),33);m=Wv(Smb(a.f,p),69);$P(a,p,m,QP)}}for(h=Uh(mX(r));Cm(h);){f=Wv(Dm(h),12);SW(f.d.f,r)||(i.c[i.c.length]=f,true)}}}A=Wv(rJ(b,(Rib(),zib)),9);if(A){for(h=Uh(mX(A));Cm(h);){f=Wv(Dm(h),12);SW(f.d.f,A)&&(i.c[i.c.length]=f,true)}}for(g=new Tob(i);g.a<g.c.c.length;){f=Wv(Rob(g),12);l=Wv(Smb(a.b,f),69);YP(a,f,l,u);for(q=new Tob(f.b);q.a<q.c.c.length;){p=Wv(Rob(q),33);m=Wv(Smb(a.f,p),69);$P(a,p,m,u)}}c=(d=Wv(rJ(b,Xhb),15).a,new HI(b.e.a+b.a.b+b.a.c+2*d,b.e.b+b.a.d+b.a.a+2*d));k=Wv(rJ(b,zib),9);if(k){k.j.a=c.a;k.j.b=c.b}j=Wv(rJ(b,PP),69);VP(a,j,Jzb,c.a);VP(a,j,Kzb,c.b);for(s=new Tob(b.b);s.a<s.c.c.length;){r=Wv(Rob(s),9);e=Wv(rJ(r,sib),55);!!e&&ZP(a,e)}}
function Xfb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H;F=new aJ;B=new aJ;r=-1;for(i=new Tob(a);i.a<i.c.c.length;){g=Wv(Rob(i),77);g.i=r--;l=0;v=0;for(f=new Tob(g.j);f.a<f.c.c.length;){d=Wv(Rob(f),117);v+=d.c}for(e=new Tob(g.d);e.a<e.c.c.length;){d=Wv(Rob(e),117);l+=d.c}g.e=l;g.k=v;v==0?(TI(B,g,B.c.b,B.c),true):l==0&&(TI(F,g,F.c.b,F.c),true)}H=new Yub((Oh(),a));m=a.c.length;q=m+1;s=m-1;o=new GU;while(H.a.Y()!=0){while(B.b!=0){A=(Bxb(B.b!=0),Wv($I(B,B.a.a),77));H.a.eb(A)!=null;A.i=s--;agb(A,F,B)}while(F.b!=0){C=(Bxb(F.b!=0),Wv($I(F,F.a.a),77));H.a.eb(C)!=null;C.i=q++;agb(C,F,B)}p=eyb;for(j=(t=(new Snb(H.a)).a.bb().mb(),new Ynb(t));j.a.G();){g=(k=Wv(j.a.H(),21),Wv(k.yb(),77));u=g.k-g.e;if(u>=p){if(u>p){o.c=xv(UF,syb,1,0,4,1);p=u}o.c[o.c.length]=g}}if(o.c.length!=0){n=Wv(yU(o,vvb(b,o.c.length)),77);H.a.eb(n)!=null;n.i=q++;agb(n,F,B);o.c=xv(UF,syb,1,0,4,1)}}w=a.c.length+1;for(h=new Tob(a);h.a<h.c.c.length;){g=Wv(Rob(h),77);g.i<m&&(g.i+=w)}for(D=new Tob(a);D.a<D.c.c.length;){C=Wv(Rob(D),77);c=new Fnb(C.j,0);while(c.b<c.d.Y()){d=(Bxb(c.b<c.d.Y()),Wv(c.d.sb(c.c=c.b++),117));G=d.b;if(C.i>G.i){vnb(c);BU(G.d,d);if(d.c>0){d.a=G;vU(G.j,d);d.b=C;vU(C.d,d)}}}}}
function OO(a){var b,c,d;for(d=new Lsb((new Fsb(a.c)).a);htb(d.a);){c=(d.b=itb(d.a),new Psb(d.c,d.b));b=Wv(c.b.b[c.a.e],62);switch(Wv(c.a,67).e){case 0:b.d=0;b.e=-(b.b+a.d);break;case 1:b.d=(a.e.e.j.a-b.c)/2;b.e=-(b.b+a.d);break;case 2:b.d=a.e.e.j.a-b.c;b.e=-(b.b+a.d);break;case 3:b.d=0;b.e=a.e.e.j.b+a.d;break;case 4:b.d=(a.e.e.j.a-b.c)/2;b.e=a.e.e.j.b+a.d;break;case 5:b.d=a.e.e.j.a-b.c;b.e=a.e.e.j.b+a.d;break;case 6:b.d=-(b.c+a.d);b.e=0;break;case 7:b.d=-(b.c+a.d);b.e=(a.e.e.j.b-b.b)/2;break;case 8:b.d=-(b.c+a.d);b.e=a.e.e.j.b-b.b;break;case 9:b.d=a.e.e.j.a+a.d;b.e=0;break;case 10:b.d=a.e.e.j.a+a.d;b.e=(a.e.e.j.b-b.b)/2;break;case 11:b.d=a.e.e.j.a+a.d;b.e=a.e.e.j.b-b.b;break;case 12:b.d=a.q.b+a.d;b.e=a.q.d+a.d;break;case 13:b.d=(a.e.e.j.a-b.c)/2;b.e=a.q.d+a.d;break;case 14:b.d=a.e.e.j.a-a.q.c-b.c-a.d;b.e=a.q.d+a.d;break;case 15:b.d=a.q.b+a.d;b.e=(a.e.e.j.b-b.b)/2;break;case 16:b.d=(a.e.e.j.a-b.c)/2;b.e=(a.e.e.j.b-b.b)/2;break;case 17:b.d=a.e.e.j.a-a.q.c-b.c-a.d;b.e=(a.e.e.j.b-b.b)/2;break;case 18:b.d=a.q.b+a.d;b.e=a.e.e.j.b-a.q.a-b.b-a.d;break;case 19:b.d=(a.e.e.j.a-b.c)/2;b.e=a.e.e.j.b-a.q.a-b.b-a.d;break;case 20:b.d=a.e.e.j.a-a.q.c-b.c-a.d;b.e=a.e.e.j.b-a.q.a-b.b-a.d;}}}
function ddb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I;F=new aJ;B=new aJ;o=-1;for(s=new Tob(a);s.a<s.c.c.length;){q=Wv(Rob(s),80);q.d=o--;i=0;v=0;for(f=new Tob(q.e);f.a<f.c.c.length;){d=Wv(Rob(f),118);v+=d.c}for(e=new Tob(q.b);e.a<e.c.c.length;){d=Wv(Rob(e),118);i+=d.c}q.c=i;q.f=v;v==0?(TI(B,q,B.c.b,B.c),true):i==0&&(TI(F,q,F.c.b,F.c),true)}H=(I=new Vwb,ml(I,a),I);j=a.c.length;p=j-1;n=j+1;l=new GU;while(H.a.c!=0){while(B.b!=0){A=(Bxb(B.b!=0),Wv($I(B,B.a.a),80));cwb(H.a,A)!=null;A.d=p--;jdb(A,F,B)}while(F.b!=0){C=(Bxb(F.b!=0),Wv($I(F,F.a.a),80));cwb(H.a,C)!=null;C.d=n++;jdb(C,F,B)}m=eyb;for(t=(h=new rwb((new wwb((new Gob(H.a)).a)).b),new Mob(h));Bnb(t.a.a);){q=(g=pwb(t.a),Wv(g.yb(),80));u=q.f-q.c;if(u>=m){if(u>m){l.c=xv(UF,syb,1,0,4,1);m=u}l.c[l.c.length]=q}}if(l.c.length!=0){k=Wv(yU(l,vvb(b,l.c.length)),80);cwb(H.a,k)!=null;k.d=n++;jdb(k,F,B);l.c=xv(UF,syb,1,0,4,1)}}w=a.c.length+1;for(r=new Tob(a);r.a<r.c.c.length;){q=Wv(Rob(r),80);q.d<j&&(q.d+=w)}for(D=new Tob(a);D.a<D.c.c.length;){C=Wv(Rob(D),80);c=new Fnb(C.e,0);while(c.b<c.d.Y()){d=(Bxb(c.b<c.d.Y()),Wv(c.d.sb(c.c=c.b++),118));G=d.b;if(C.d>G.d){vnb(c);BU(G.b,d);if(d.c>0){d.a=G;vU(G.e,d);d.b=C;vU(C.b,d)}}}}}
function e0(a){switch(a.e){case 14:return new wY;case 37:return new SY;case 8:return new YY;case 30:return new cZ;case 38:return new qZ;case 3:return new tZ;case 47:case 1:return new SZ((XZ(),WZ));case 4:return new wZ;case 49:return new AZ;case 23:return new $5;case 13:return new d$;case 34:return new j$;case 40:return new w$;case 35:return new F$;case 44:return new o4;case 28:return new I$;case 39:return new L$;case 27:return new N$;case 6:return new R$;case 31:return new m0;case 9:return new q0;case 43:return new w0;case 17:return new A0;case 18:return new G0;case 29:return new S0;case 11:return new q1;case 12:return new Z0;case 36:return new _0;case 46:case 0:return new SZ((XZ(),VZ));case 41:return new b1;case 15:return new e1;case 33:return new k1;case 42:return new R1;case 22:return new X1;case 19:return new k0;case 10:return new _1;case 7:return new c2;case 24:return new f2;case 21:return new h2;case 16:return new n2;case 45:return new q2;case 26:return new x2;case 20:return new A2;case 25:return new H2;case 5:return new l3;case 32:return new u3;case 48:case 2:return new SZ((XZ(),UZ));default:throw new slb('No implementation is available for the layout processor '+(a.d!=null?a.d:''+a.e));}}
function PO(a){var b,c,d,e,f,g,h;c=a.e.e.j;a.b?(b=Wv(oW(a.e,(eM(),jL)),65)):(b=new EP(a.k,a.k,a.k,a.k));e=c.a;(a.b||a.g[1]!=(zM(),xM))&&(e-=b.b+b.c);f=c.a;(a.b||a.g[3]!=(zM(),xM))&&(f-=b.b+b.c);g=c.b;(a.b||a.g[4]!=(zM(),xM))&&(g-=b.d+b.a);d=c.b;(a.b||a.g[2]!=(zM(),xM))&&(d-=b.d+b.a);if(aP(a,(sN(),$M))==(zM(),xM)){a.j[1]=(e-dP(a,$M))/bP(a,$M);a.f=a.b?b.b+(eP(a,$M)==1?a.j[1]:0):a.j[1]}else{a.j[1]=a.k;h=dP(a,$M)+a.j[1]*(eP(a,$M)-1);switch(aP(a,$M).e){case 2:a.f=b.b;break;case 3:a.f=b.b+(e-h)/2;break;case 4:a.f=c.a-h-b.c;}}if(aP(a,pN)==xM){a.j[3]=(f-dP(a,pN))/bP(a,pN);a.r=c.a-(a.b?b.c+(eP(a,pN)==1?a.j[3]:0):a.j[3])}else{a.j[3]=a.k;h=dP(a,pN)+a.j[3]*(eP(a,pN)-1);switch(aP(a,pN).e){case 2:a.r=h+b.b;break;case 3:a.r=c.a-(f-h)/2-b.c;break;case 4:a.r=c.a-b.c;}}if(aP(a,rN)==xM){a.j[4]=(g-dP(a,rN))/bP(a,rN);a.s=c.b-(a.b?b.a+(eP(a,rN)==1?a.j[4]:0):a.j[4])}else{a.j[4]=a.k;h=dP(a,rN)+a.j[4]*(eP(a,rN)-1);switch(aP(a,rN).e){case 2:a.s=h+b.d;break;case 3:a.s=c.b-(g-h)/2-b.a;break;case 4:a.s=c.b-b.a;}}if(aP(a,ZM)==xM){a.j[2]=(d-dP(a,ZM))/bP(a,ZM);a.a=a.b?b.d+(eP(a,ZM)==1?a.j[2]:0):a.j[2]}else{a.j[2]=a.k;h=dP(a,ZM)+a.j[2]*(eP(a,ZM)-1);switch(aP(a,ZM).e){case 2:a.a=b.d;break;case 3:a.a=b.d+(d-h)/2;break;case 4:a.a=c.b-h-b.a;}}}
function hab(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I;G=0;g=0;l=b[0].d;B=c[0].d;for(o=0,q=c.length;o<q;++o){m=c[o];if(LM(Wv(rJ(m,(eM(),TL)),28))){s=0;for(v=new Tob(m.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);if(u.g==(sN(),$M)){for(f=new Tob(u.b);f.a<f.c.c.length;){e=Wv(Rob(f),12);if(e.c.f.d==l){++s;break}}}else{break}}t=0;A=new Fnb(m.f,m.f.c.length);while(A.b>0){u=(Bxb(A.b>0),Wv(A.a.sb(A.c=--A.b),7));w=0;for(f=new Tob(u.b);f.a<f.c.c.length;){e=Wv(Rob(f),12);e.c.f.d==l&&++w}if(w>0){if(u.g==(sN(),$M)){a.a[u.k]=G;++G}else{a.a[u.k]=G+s+t;++t}g+=w}}G+=t}else{r=0;for(v=new Tob(m.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);for(f=new Tob(u.b);f.a<f.c.c.length;){e=Wv(Rob(f),12);e.c.f.d==l&&++r}a.a[u.k]=G}if(r>0){++G;g+=r}}}C=xv(mw,Yyb,26,g,12,1);i=0;for(n=0,p=b.length;n<p;++n){m=b[n];if(LM(Wv(rJ(m,(eM(),TL)),28))){for(v=new Tob(m.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);D=i;for(f=new Tob(u.e);f.a<f.c.c.length;){e=Wv(Rob(f),12);F=e.d;F.f.d==B&&kab(C,D,i++,a.a[F.k])}}}else{D=i;for(v=new Tob(m.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);for(f=new Tob(u.e);f.a<f.c.c.length;){e=Wv(Rob(f),12);F=e.d;F.f.d==B&&kab(C,D,i++,a.a[F.k])}}}}h=1;while(h<G){h*=2}I=2*h-1;h-=1;H=xv(mw,Yyb,26,I,12,1);d=0;for(k=0;k<g;k++){j=C[k]+h;++H[j];while(j>0){j%2>0&&(d+=H[j+1]);j=(j-1)/2|0;++H[j]}}return d}
function BV(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J;nI(b,'Compound graph postprocessor',1);c=Ckb(Ixb(Xv(rJ(a,(Mjb(),gjb)))));h=Wv(rJ(a,(Rib(),bib)),144);l=new vtb;for(w=h.W().mb();w.G();){v=Wv(w.H(),12);g=new IU(h.U(v));Gpb(g,new $V(a));F=VV((Cxb(0,g.c.length),Wv(g.c[0],114)));H=WV(Wv(yU(g,g.c.length-1),114));_I(v.a);C=F.f;SW(H.f,C)?(B=Wv(rJ(C,sib),55)):(B=hX(C));o=Wv(rJ(v,(eM(),CL)),44);if(ol(g,zV)){if(!o){o=new jJ;sJ(v,CL,o)}else{_I(o)}}else !!o&&sJ(v,CL,null);q=null;for(f=new Tob(g);f.a<f.c.c.length;){e=Wv(Rob(f),114);u=new FI;MW(u,e.a,B);r=e.b;d=new jJ;gJ(d,0,r.a);hJ(d,u);D=new II(MX(r.c));G=new II(MX(r.d));D.a+=u.a;D.b+=u.b;G.a+=u.a;G.b+=u.b;if(q){d.b==0?(t=G):(t=(Bxb(d.b!=0),Wv(d.a.a.c,10)));I=Jlb(q.a-t.a)>dAb;J=Jlb(q.b-t.b)>dAb;(!c&&I&&J||c&&(I||J))&&QI(v.a,D)}Ue(v.a,d);d.b==0?(q=D):(q=(Bxb(d.b!=0),Wv(d.c.b.c,10)));s=Wv(rJ(r,CL),44);if(s){n=new jJ;gJ(n,0,s);hJ(n,u);Ue(o,n)}if(WV(e)==H){if(hX(H.f)!=e.a){u=new FI;MW(u,hX(H.f),B)}sJ(v,Pib,u)}p=new Fnb(r.b,0);while(p.b<p.d.Y()){i=(Bxb(p.b<p.d.Y()),Wv(p.d.sb(p.c=p.b++),33));if(gw(rJ(i,xib))!==gw(v)){continue}MW(i.i,hX(r.c.f),B);vnb(p);vU(v.b,i)}l.a.db(r,l)}dW(v,F);eW(v,H)}for(k=(A=(new Snb(l.a)).a.bb().mb(),new Ynb(A));k.a.G();){j=(m=Wv(k.a.H(),21),Wv(m.yb(),12));dW(j,null);eW(j,null)}pI(b)}
function c$(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I;C=Wv(rJ(a,(eM(),TL)),28);if(!(C!=(KM(),IM)&&C!=JM)){return}p=a.c;o=p.c.length;l=new HU((Mh(o+2,Uyb),$s(PH(PH(5,o+2),(o+2)/10|0))));q=new HU((Mh(o+2,Uyb),$s(PH(PH(5,o+2),(o+2)/10|0))));vU(l,new ntb);vU(l,new ntb);vU(q,new GU);vU(q,new GU);A=new vtb;for(b=0;b<o;b++){c=(Cxb(b,p.c.length),Wv(p.c[b],16));D=(Cxb(b,l.c.length),Wv(l.c[b],57));r=(mp(),new ntb);l.c[l.c.length]=r;G=(Cxb(b,q.c.length),Wv(q.c[b],20));t=new GU;q.c[q.c.length]=t;for(e=new Tob(c.a);e.a<e.c.c.length;){d=Wv(Rob(e),9);for(j=Uh(iX(d));Cm(j);){h=Wv(Dm(j),12);H=h.c.f;if(!_Z(H)){continue}A.a.db(H,A);F=Wv(D.cb(rJ(H,(Rib(),uib))),9);if(!F){F=$Z(a,H);D.db(rJ(H,uib),F);G.ib(F)}dW(h,Wv(yU(F.f,1),7))}for(i=Uh(mX(d));Cm(i);){h=Wv(Dm(i),12);I=h.d.f;if(!_Z(I)){continue}A.a.db(I,A);s=Wv(Smb(r,rJ(I,(Rib(),uib))),9);if(!s){s=$Z(a,I);Umb(r,rJ(I,uib),s);t.c[t.c.length]=s}eW(h,Wv(yU(s.f,0),7))}}}for(m=0;m<q.c.length;m++){u=(Cxb(m,q.c.length),Wv(q.c[m],20));if(u.V()){continue}if(m==0){n=new sY(a);Fxb(0,p.c.length);fxb(p.c,0,n)}else if(m==l.c.length-1){n=new sY(a);p.c[p.c.length]=n}else{n=(Cxb(m-1,p.c.length),Wv(p.c[m-1],16))}for(g=u.mb();g.G();){f=Wv(g.H(),9);rX(f,n)}}for(w=(B=(new Snb(A.a)).a.bb().mb(),new Ynb(B));w.a.G();){v=(k=Wv(w.a.H(),21),Wv(k.yb(),9));rX(v,null)}}
function Pab(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J,K;I=new GU;for(o=new Tob(b.c);o.a<o.c.c.length;){m=Wv(Rob(o),16);for(v=new Tob(m.a);v.a<v.c.c.length;){u=Wv(Rob(v),9);u.k=-1;l=eyb;B=eyb;for(D=new Tob(u.f);D.a<D.c.c.length;){C=Wv(Rob(D),7);for(e=new Tob(C.b);e.a<e.c.c.length;){c=Wv(Rob(e),12);F=Wv(rJ(c,(Rib(),Eib)),24).a;l=l>F?l:F}for(d=new Tob(C.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);F=Wv(rJ(c,(Rib(),Eib)),24).a;B=B>F?B:F}}sJ(u,Fab,Elb(l));sJ(u,Gab,Elb(B))}}r=0;for(n=new Tob(b.c);n.a<n.c.c.length;){m=Wv(Rob(n),16);for(v=new Tob(m.a);v.a<v.c.c.length;){u=Wv(Rob(v),9);if(u.k<0){H=new Wab;H.b=r++;Mab(a,u,H);I.c[I.c.length]=H}}}A=Do(I.c.length);k=Do(I.c.length);for(g=0;g<I.c.length;g++){vU(A,new GU);vU(k,Elb(0))}Kab(b,I,A,k);J=Wv(FU(I,xv(wE,NAb,111,I.c.length,0,1)),625);w=Wv(FU(A,xv(sH,{3:1,5:1,6:1,672:1},20,A.c.length,0,1)),672);j=xv(mw,Yyb,26,k.c.length,12,1);for(h=0;h<j.length;h++){j[h]=(Cxb(h,k.c.length),Wv(k.c[h],24)).a}s=0;t=new GU;for(i=0;i<J.length;i++){j[i]==0&&vU(t,J[i])}q=xv(mw,Yyb,26,J.length,12,1);while(t.c.length!=0){H=Wv(AU(t,0),111);q[H.b]=s++;while(!w[H.b].V()){K=Wv(w[H.b].vb(0),111);--j[K.b];j[K.b]==0&&(t.c[t.c.length]=K,true)}}a.a=xv(wE,NAb,111,J.length,0,1);for(f=0;f<J.length;f++){p=J[f];G=q[f];a.a[G]=p;p.b=G;for(v=new Tob(p.f);v.a<v.c.c.length;){u=Wv(Rob(v),9);u.k=G}}return a.a}
function JP(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C;nI(b,'Fixed Layout',1);i=Wv(rJ(a,(eM(),uL)),122);p=0;q=0;for(t=new Tob(a.b);t.a<t.c.c.length;){r=Wv(Rob(t),9);B=Wv(rJ(r,YL),10);if(B){r.i.a=B.a;r.i.b=B.b;if(Wv(rJ(r,aM),86).kb((DN(),zN))){C=Wv(rJ(r,IL),15).a;j=Wv(rJ(r,HL),15).a;C>0&&j>0&&WW(r,new HI(C,j),true)}}p=Nlb(p,r.i.a+r.j.a);q=Nlb(q,r.i.b+r.j.b);for(n=new Tob(r.c);n.a<n.c.c.length;){l=Wv(Rob(n),33);B=Wv(rJ(l,YL),10);if(B){l.i.a=B.a;l.i.b=B.b}p=Nlb(p,r.i.a+l.i.a+l.j.a);q=Nlb(q,r.i.b+l.i.b+l.j.b)}for(v=new Tob(r.f);v.a<v.c.c.length;){u=Wv(Rob(v),7);B=Wv(rJ(u,YL),10);if(B){u.i.a=B.a;u.i.b=B.b}w=r.i.a+u.i.a;A=r.i.b+u.i.b;p=Nlb(p,w+u.j.a);q=Nlb(q,A+u.j.b);for(m=new Tob(u.c);m.a<m.c.c.length;){l=Wv(Rob(m),33);B=Wv(rJ(l,YL),10);if(B){l.i.a=B.a;l.i.b=B.b}p=Nlb(p,w+l.i.a+l.j.a);q=Nlb(q,A+l.i.b+l.j.b)}}for(h=Uh(mX(r));Cm(h);){f=Wv(Dm(h),12);o=KP(f);p=Nlb(p,o.a);q=Nlb(q,o.b)}for(g=Uh(iX(r));Cm(g);){f=Wv(Dm(g),12);if(gw(rJ(f.c.f,(Rib(),sib)))!==gw(a)){o=KP(f);p=Nlb(p,o.a);q=Nlb(q,o.b)}}}if(i==(NK(),JK)){for(s=new Tob(a.b);s.a<s.c.c.length;){r=Wv(Rob(s),9);for(g=Uh(mX(r));Cm(g);){f=Wv(Dm(g),12);k=LP(f);k.b==0?sJ(f,CL,null):sJ(f,CL,k)}}}a.e.a=p;a.e.b=q;sJ(a,aM,(DN(),d=Wv(Hkb(Lz),11),new atb(d,Wv(exb(d,d.length),11),0)));e=Wv(rJ(a,(Rib(),zib)),9);!!e&&sJ(e,aM,(c=Wv(Hkb(Lz),11),new atb(c,Wv(exb(c,c.length),11),0)));pI(b)}
function Y8(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G;if(!LM(Wv(rJ(b,(eM(),TL)),28))){if(b.f.c.length>1){A=xv(LF,Txb,15,a.a.length,0,1);j=Do(a.a.length);p=0;o=0;c=2*b.d.a.c.length+1;H:for(w=new Tob(b.f);w.a<w.c.c.length;){v=Wv(Rob(w),7);r=v.g==(sN(),$M)||v.g==pN;G=0;if(r){B=Wv(rJ(v,(Rib(),Bib)),9);if(!B){continue}m=false;u=false;for(D=new Tob(B.f);D.a<D.c.c.length;){C=Wv(Rob(D),7);gw(rJ(C,uib))===gw(v)&&(C.e.c.length==0?C.b.c.length==0||(m=true):(u=true))}m&&!u?(G=v.g==$M?-(!B.d?-1:zU(B.d.a,B,0)):c-(!B.d?-1:zU(B.d.a,B,0))):u&&!m?(G=(!B.d?-1:zU(B.d.a,B,0))+1):m&&u&&(G=v.g==$M?0:c/2)}else{for(t=new Tob(v.e);t.a<t.c.c.length;){s=Wv(Rob(t),12);e=s.d;if(e.f.d==b.d){j.c[j.c.length]=v;continue H}else{G+=a.a[e.k]}}for(l=new Tob(v.b);l.a<l.c.c.length;){k=Wv(Rob(l),12);e=k.c;if(e.f.d==b.d){j.c[j.c.length]=v;continue H}else{G-=a.a[e.k]}}}if(v.b.c.length+v.e.c.length>0){A[v.k]=new llb(G/(v.b.c.length+v.e.c.length));p=Rlb(p,A[v.k].a);o=Olb(o,A[v.k].a)}else r&&(A[v.k]=new llb(G))}q=(!b.d?-1:zU(b.d.a,b,0))+1;n=b.d.a.c.length+1;for(i=new Tob(j);i.a<i.c.c.length;){h=Wv(Rob(i),7);G=0;g=0;for(f=Uh(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[new fY(h),new lY(h)]))))));Cm(f);){e=Wv(Dm(f),7);if(e.f.d==b.d){G+=jX(e.f)+1;++g}}d=G/g;F=h.g;F==(sN(),ZM)?d<q?(A[h.k]=new llb(p-d)):(A[h.k]=new llb(o+(n-d))):F==rN&&(d<q?(A[h.k]=new llb(o+d)):(A[h.k]=new llb(p-(n-d))))}Gpb(b.f,new a9(A))}sJ(b,TL,(KM(),EM))}}
function O4(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C;B=new GU;a.a.b.c=xv(UF,syb,1,0,4,1);u=(mp(),new ntb);for(r=new Tob(a.d.c);r.a<r.c.c.length;){p=Wv(Rob(r),16);for(t=new Tob(p.a);t.a<t.c.c.length;){s=Wv(Rob(t),9);if(Ckb(Ixb(Xv(rJ(s,(eM(),qL)))))){if(!sl(gX(s))){h=Wv(ql(gX(s)),12);v=h.c.f;v==s&&(v=h.d.f);w=new RJ(v,EI(xI(s.i),v.i));Umb(a.b,s,w);continue}}f=new Q3(s,a.d);vU(a.a.b,f);Ltb(u.d,s,f)}}for(q=new Tob(a.d.c);q.a<q.c.c.length;){p=Wv(Rob(q),16);for(t=new Tob(p.a);t.a<t.c.c.length;){s=Wv(Rob(t),9);f=Wv(re(Ktb(u.d,s)),25);for(k=Uh(mX(s));Cm(k);){i=Wv(Dm(k),12);d=WI(i.a,0);l=true;o=null;if(d.b!=d.d.c){b=Wv(_ub(d),10);if(i.c.g==(sN(),$M)){C=new X4(b,new HI(b.a,f.j.e),f,i);C.c=true;B.c[B.c.length]=C}if(i.c.g==pN){C=new X4(b,new HI(b.a,f.j.e+f.j.b),f,i);C.d=true;B.c[B.c.length]=C}while(d.b!=d.d.c){c=Wv(_ub(d),10);if(!RR(b.b,c.b)){o=new X4(b,c,null,i);B.c[B.c.length]=o;if(l){l=false;if(c.b<f.j.e){o.c=true}else if(c.b>f.j.e+f.j.b){o.d=true}else{o.d=true;o.c=true}}}d.b!=d.d.c&&(b=c)}if(o){g=Wv(Smb(u,i.d.f),25);if(b.b<g.j.e){o.c=true}else if(b.b>g.j.e+g.j.b){o.d=true}else{o.d=true;o.c=true}}}}for(j=Uh(iX(s));Cm(j);){i=Wv(Dm(j),12);if(i.a.b!=0){b=Wv(VI(i.a),10);if(i.d.g==(sN(),$M)){C=new X4(b,new HI(b.a,f.j.e),f,i);C.c=true;B.c[B.c.length]=C}if(i.d.g==pN){C=new X4(b,new HI(b.a,f.j.e+f.j.b),f,i);C.d=true;B.c[B.c.length]=C}}}}}if(B.c.length!=0){ypb();Gpb(B,null);n=(Cxb(0,B.c.length),Wv(B.c[0],142));e=new L3(n,a.d);for(m=1;m<B.c.length;m++){A=(Cxb(m,B.c.length),Wv(B.c[m],142));if(RR(e.j.d,A.j)&&!(TR(e.j.e+e.j.b,A.k)||TR(A.n,e.j.e))){K3(e,A)}else{vU(a.a.b,e);e=new L3(A,a.d)}}vU(a.a.b,e)}B.c=xv(UF,syb,1,0,4,1);N4(a)}
function eZ(a,b,c,d,e,f){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J,K,L,M;h=Wv(yU(a.d.c.c,d),16);K=new vtb;o=new vtb;for(n=0;n<h.a.c.length;++n){s=Wv(yU(h.a,n),9);n<c?(D=K.a.db(s,K),D==null):n>c&&(C=o.a.db(s,o),C==null)}L=new vtb;p=new vtb;for(u=(G=(new Snb(K.a)).a.bb().mb(),new Ynb(G));u.a.G();){s=(l=Wv(u.a.H(),21),Wv(l.yb(),9));g=b==1?mX(s):iX(s);for(j=(Il(),new Im(Dl(ul(g.a,new yl))));Cm(j);){i=Wv(Dm(j),12);rY(s.d)!=rY(i.d.f.d)&&stb(L,i.d.f)}}for(v=(H=(new Snb(o.a)).a.bb().mb(),new Ynb(H));v.a.G();){s=(l=Wv(v.a.H(),21),Wv(l.yb(),9));g=b==1?mX(s):iX(s);for(j=(Il(),new Im(Dl(ul(g.a,new yl))));Cm(j);){i=Wv(Dm(j),12);rY(s.d)!=rY(i.d.f.d)&&stb(p,i.d.f)}}if(aZ){Fmb()}B=Wv(yU(a.d.c.c,d+(b==1?1:-1)),16);q=eyb;r=$xb;for(m=0;m<B.a.c.length;m++){s=Wv(yU(B.a,m),9);L.a.R(s)?(q=q>m?q:m):p.a.R(s)&&(r=r<m?r:m)}if(q<r){for(w=(I=(new Snb(L.a)).a.bb().mb(),new Ynb(I));w.a.G();){s=(l=Wv(w.a.H(),21),Wv(l.yb(),9));for(k=Uh(mX(s));Cm(k);){i=Wv(Dm(k),12);if(rY(s.d)==rY(i.d.f.d)){return null}}for(j=Uh(iX(s));Cm(j);){i=Wv(Dm(j),12);if(rY(s.d)==rY(i.c.f.d)){return null}}}for(A=(F=(new Snb(p.a)).a.bb().mb(),new Ynb(F));A.a.G();){s=(l=Wv(A.a.H(),21),Wv(l.yb(),9));for(k=Uh(mX(s));Cm(k);){i=Wv(Dm(k),12);if(rY(s.d)==rY(i.d.f.d)){return null}}for(j=Uh(iX(s));Cm(j);){i=Wv(Dm(j),12);if(rY(s.d)==rY(i.c.f.d)){return null}}}K.a.Y()==0?(M=0):o.a.Y()==0?(M=B.a.c.length):(M=q+1);for(t=new Tob(h.a);t.a<t.c.c.length;){s=Wv(Rob(t),9);if(s.g==(CX(),BX)){return null}}if(f==1){return Co(Bv(tv(PF,1),Txb,24,0,[Elb(M)]))}else if(b==1&&d==e-2||b==0&&d==1){return Co(Bv(tv(PF,1),Txb,24,0,[Elb(M)]))}else{J=eZ(a,b,M,d+(b==1?1:-1),e,f-1);!!J&&b==1&&J.rb(0,Elb(M));return J}}return null}
function aQ(b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;SP(c);o=(eM(),KL).b;if(o in c.a&&Pu(c,o).ic().a){return}j=Pu(c,'source');k=Pu(c,'sourcePort');l=Pu(c,'target');m=Pu(c,'targetPort');if(!j){throw new GQ("Edges must contain a 'source' property.",null,c)}else if(!j.lc()){throw new GQ("Invalid format of an edge's 'source' property. It must be a string.",j,c)}if(!l){throw new GQ("Edges must contain a 'target' property.",null,c)}else if(!l.lc()){throw new GQ("Invalid format of an edge's 'target' property. It must be a string.",l,c)}r=null;t=null;try{q=Wv(Tmb(b.i,j.lc().a),9);!!k&&!!k.lc()&&(r=Wv(Tmb(b.k,k.lc().a),7));s=Wv(Tmb(b.i,l.lc().a),9);!!m&&!!m.lc()&&(t=Wv(Tmb(b.k,m.lc().a),7))}catch(a){a=OH(a);if(aw(a,76)){throw new FQ("An edge's 'source', 'target', 'sourcePort', and 'targetPort' properties have to be strings.",c)}else throw NH(a)}if(!Ckb(Ixb(b.g))){if(!q||!s){return}else if(hX(q)!=hX(s)){return}}if(!q||!s){throw new FQ("An edge's source or target node could not be resolved.",c)}p=hX(q);e=new hW;sJ(e,(Rib(),uib),c);h=Wv(Pu(c,'id'),97);Vmb(b.a,h.a,e);Umb(b.b,e,c);hQ(c,e);dQ(b,c,e,p);f=Wv(rJ(p,jib),18);q==s&&f.ib((ohb(),nhb));if(!r){r=OW(q,new FI,(djb(),bjb),p)}else if(r.f!=q){throw new EQ('Inconsistent source port reference found.')}if(!t){t=OW(s,new FI,(djb(),ajb),p)}else if(t.f!=s){throw new EQ('Inconsistent target port reference found.')}dW(e,r);eW(e,t);(tl(Sh((Gi(),new gr(Ti(Bv(tv(UF,1),syb,1,4,[r.b,r.e]))))))>1||tl(Sh(new gr(Ti(Bv(tv(UF,1),syb,1,4,[t.b,t.e])))))>1)&&f.ib((ohb(),ihb));if(gw(rJ(p,(Mjb(),kjb)))===gw((p9(),n9))&&!(Hzb in c.a)){d=new jJ;try{i=Pu(c,Hzb).hc();for(g=0;g<i.a.length;++g){n=gu(i,g).kc();u=new HI(Pu(n,'x').jc().a,Pu(n,'y').jc().a);TI(d,u,d.c.b,d.c)}sJ(e,vib,d)}catch(a){a=OH(a);if(aw(a,54)){throw new FQ("Invalid format of an edges 'bendPoints' property.",c)}else throw NH(a)}}sJ(e,CL,null)}
function d0(){d0=iI;L_=new f0('LEFT_DIR_PREPROCESSOR',0);o_=new f0('DOWN_DIR_PREPROCESSOR',1);c0=new f0('UP_DIR_PREPROCESSOR',2);m_=new f0('COMMENT_PREPROCESSOR',3);p_=new f0('EDGE_AND_LAYER_CONSTRAINT_EDGE_REVERSER',4);__=new f0('SPLINE_SELF_LOOP_PREPROCESSOR',5);z_=new f0('INTERACTIVE_EXTERNAL_PORT_POSITIONER',6);T_=new f0('PARTITION_PREPROCESSOR',7);j_=new f0('BIG_NODES_PREPROCESSOR',8);D_=new f0('LABEL_DUMMY_INSERTER',9);S_=new f0('PARTITION_POSTPROCESSOR',10);P_=new f0('NODE_PROMOTION',11);I_=new f0('LAYER_CONSTRAINT_PROCESSOR',12);s_=new f0('HIERARCHICAL_PORT_CONSTRAINT_PROCESSOR',13);h_=new f0('BIG_NODES_INTERMEDIATEPROCESSOR',14);N_=new f0('LONG_EDGE_SPLITTER',15);W_=new f0('PORT_SIDE_PROCESSOR',16);F_=new f0('LABEL_DUMMY_SWITCHER',17);G_=new f0('LABEL_MANAGEMENT_PROCESSOR',18);A_=new f0('INVERTED_PORT_PROCESSOR',19);Z_=new f0('SELF_LOOP_PROCESSOR',20);V_=new f0('PORT_LIST_SORTER',21);R_=new f0('NORTH_SOUTH_PORT_PREPROCESSOR',22);r_=new f0('GREEDY_SWITCH',23);U_=new f0('PORT_DISTRIBUTER',24);$_=new f0('SPLINE_SELF_LOOP_POSITIONER',25);Y_=new f0('SAUSAGE_COMPACTION',26);B_=new f0('IN_LAYER_CONSTRAINT_PROCESSOR',27);x_=new f0('HYPEREDGE_DUMMY_MERGER',28);H_=new f0('LABEL_SIDE_SELECTOR',29);k_=new f0('BIG_NODES_SPLITTER',30);C_=new f0('LABEL_AND_NODE_SIZE_PROCESSOR',31);a0=new f0('SPLINE_SELF_LOOP_ROUTER',32);O_=new f0('NODE_MARGIN_CALCULATOR',33);t_=new f0('HIERARCHICAL_PORT_DUMMY_SIZE_PROCESSOR',34);v_=new f0('HIERARCHICAL_PORT_POSITION_PROCESSOR',35);J_=new f0('LAYER_SIZE_AND_GRAPH_HEIGHT_CALCULATOR',36);i_=new f0('BIG_NODES_POSTPROCESSOR',37);l_=new f0('COMMENT_POSTPROCESSOR',38);y_=new f0('HYPERNODE_PROCESSOR',39);u_=new f0('HIERARCHICAL_PORT_ORTHOGONAL_EDGE_ROUTER',40);M_=new f0('LONG_EDGE_JOINER',41);Q_=new f0('NORTH_SOUTH_PORT_POSTPROCESSOR',42);E_=new f0('LABEL_DUMMY_REMOVER',43);w_=new f0('HORIZONTAL_COMPACTOR',44);X_=new f0('REVERSED_EDGE_RESTORER',45);K_=new f0('LEFT_DIR_POSTPROCESSOR',46);n_=new f0('DOWN_DIR_POSTPROCESSOR',47);b0=new f0('UP_DIR_POSTPROCESSOR',48);q_=new f0('END_LABEL_PROCESSOR',49)}
function Rib(){Rib=iI;var a,b;uib=new CJ('origin');_hb=new CJ('processingConfiguration');Fib=new CJ('processors');$hb=new DJ('compoundNode',(xkb(),xkb(),vkb));lib=new DJ('insideConnections',(null,vkb));sib=new CJ('nestedLGraph');zib=new CJ('parentLNode');vib=new CJ('originalBendpoints');wib=new CJ('originalDummyNodePosition');xib=new CJ('originalLabelEdge');Hib=new CJ('representedLabels');pib=new DJ('labelSide',(kP(),jP));Iib=new DJ('reversed',(null,vkb));Gib=new CJ('random');qib=new DJ('longEdgeSource',null);rib=new DJ('longEdgeTarget',null);dib=new DJ('edgeConstraint',(Hgb(),Fgb));nib=new CJ('inLayerLayoutUnit');mib=new DJ('inLayerConstraint',(Hhb(),Fhb));oib=new DJ('inLayerSuccessorConstraint',new GU);Bib=new CJ('portDummy');aib=new DJ('crossingHint',Elb(0));jib=new DJ('graphProperties',(b=Wv(Hkb(mF),11),new atb(b,Wv(exb(b,b.length),11),0)));hib=new DJ('externalPortSide',(sN(),qN));iib=new DJ('externalPortSize',new FI);gib=new CJ('externalPortReplacedDummy');fib=new DJ('externalPortConnections',(a=Wv(Hkb(Kz),11),new atb(a,Wv(exb(a,a.length),11),0)));Cib=new DJ(yzb,0);Shb=new CJ('barycenterAssociates');Qib=new CJ('TopSideComments');Yhb=new CJ('BottomSideComments');Zhb=new CJ('CommentConnectionPort');kib=new DJ('inputCollect',(null,vkb));yib=new DJ('outputCollect',(null,vkb));cib=new DJ('cyclic',(null,vkb));Whb=new DJ('bigNodeOriginalSize',new llb(0));Vhb=new DJ('bigNodeInitial',(null,vkb));Thb=new DJ('de.cau.cs.kieler.klay.layered.bigNodeLabels',new GU);Uhb=new DJ('de.cau.cs.kieler.klay.layered.postProcess',null);bib=new CJ('crossHierarchyMap');Pib=new CJ('targetOffset');Lib=new DJ('splineLabelSize',new FI);Mib=new DJ('splineLoopSide',(Ieb(),Feb));Nib=new DJ('splineSelfLoopComponents',new GU);Oib=new DJ('splineSelfLoopMargins',new DP);Kib=new CJ('spacings');Aib=new DJ('partitionConstraint',(null,vkb));tib=new AJ((eM(),LL),new llb(0));Jib=new BJ(cM,new llb(20),new llb(1));Dib=new BJ(XL,new llb(10),new llb(1));Xhb=new BJ(pL,new llb(12),new llb(0));Eib=new AJ(ZL,Elb(0));Rhb=new BJ(nL,new llb(cAb),new llb(0));eib=new AJ(uL,(NK(),JK))}
function Mjb(){Mjb=iI;Bjb=new DJ('de.cau.cs.kieler.klay.layered.nodePromotion',(I1(),G1));Cjb=new FJ('de.cau.cs.kieler.klay.layered.nodePromotionBoundary',Elb(0),Elb(0),Elb(100));Hjb=new DJ(vzb,Elb(1));Ejb=new EJ('de.cau.cs.kieler.klay.layered.inLayerSpacingFactor',new llb(1),new llb(0));qjb=new DJ('de.cau.cs.kieler.klay.layered.edgeSpacingFactor',new llb(0.5));pjb=new DJ('de.cau.cs.kieler.klay.layered.edgeNodeSpacingFactor',new llb(IAb));njb=new DJ('de.cau.cs.kieler.klay.layered.distributeNodes',(xkb(),xkb(),vkb));Ljb=new DJ('de.cau.cs.kieler.klay.layered.wideNodesOnMultipleLayers',(ckb(),bkb));ljb=new DJ('de.cau.cs.kieler.klay.layered.cycleBreaking',(Z7(),X7));zjb=new DJ('de.cau.cs.kieler.klay.layered.nodeLayering',(x8(),w8));kjb=new DJ('de.cau.cs.kieler.klay.layered.crossMin',(p9(),o9));tjb=new DJ('de.cau.cs.kieler.klay.layered.greedySwitch',(zhb(),whb));Ajb=new DJ('de.cau.cs.kieler.klay.layered.nodePlace',(kbb(),fbb));wjb=new FJ('de.cau.cs.kieler.klay.layered.linearSegmentsDeflectionDampening',new llb(HAb),new llb(0),new llb(1));sjb=new DJ('de.cau.cs.kieler.klay.layered.fixedAlignment',(_gb(),Ygb));ojb=new DJ('de.cau.cs.kieler.klay.layered.edgeLabelSideSelection',(Pgb(),Lgb));mjb=new DJ(uzb,(null,vkb));Kjb=new EJ('de.cau.cs.kieler.klay.layered.thoroughness',Elb(10),Elb(1));vjb=new DJ('de.cau.cs.kieler.klay.layered.layerConstraint',(Xib(),Wib));xjb=new DJ('de.cau.cs.kieler.klay.layered.mergeEdges',(null,vkb));yjb=new DJ('de.cau.cs.kieler.klay.layered.mergeHierarchyEdges',(null,wkb));ujb=new DJ('de.cau.cs.kieler.klay.layered.interactiveReferencePoint',(Mhb(),Khb));rjb=new DJ('de.cau.cs.kieler.klay.layered.feedBackEdges',(null,vkb));gjb=new DJ('de.cau.cs.kieler.klay.layered.unnecessaryBendpoints',(null,vkb));jjb=new DJ('de.cau.cs.kieler.klay.layered.contentAlignment',(zgb(),Vsb(ygb,Bv(tv(iF,1),uyb,123,0,[ugb]))));Ijb=new DJ('de.cau.cs.kieler.klay.layered.sausageFolding',(null,vkb));Jjb=new DJ('de.cau.cs.kieler.klay.layered.splines.selfLoopPlacement',(Qjb(),Pjb));hjb=new DJ('de.cau.cs.kieler.klay.layered.nodeplace.compactionStrategy',(lcb(),jcb));Djb=new DJ('de.cau.cs.kieler.klay.layered.northOrSouthPort',(null,vkb));Fjb=new DJ('de.cau.cs.kieler.klay.layered.postCompaction',(g4(),e4));Gjb=new DJ('de.cau.cs.kieler.klay.layered.postCompaction.constraints',(X3(),W3));ijb=new DJ('de.cau.cs.kieler.klay.layered.components.compact',(null,vkb))}
function uO(){uO=iI;rO=new vO('OUT_T_L',0,(Gi(),new Er(Vsb((oM(),kM),Bv(tv(Gz,1),uyb,41,0,[nM,gM])))),(DO(),BO));qO=new vO('OUT_T_C',1,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[nM,fM])),Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[nM,fM,hM]))]))),AO);sO=new vO('OUT_T_R',2,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[nM,iM]))),CO);iO=new vO('OUT_B_L',3,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[lM,gM]))),BO);hO=new vO('OUT_B_C',4,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[lM,fM])),Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[lM,fM,hM]))]))),AO);jO=new vO('OUT_B_R',5,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[lM,iM]))),CO);mO=new vO('OUT_L_T',6,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[gM,nM,hM]))),CO);lO=new vO('OUT_L_C',7,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[gM,mM])),Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[gM,mM,hM]))]))),CO);kO=new vO('OUT_L_B',8,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[gM,lM,hM]))),CO);pO=new vO('OUT_R_T',9,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[iM,nM,hM]))),BO);oO=new vO('OUT_R_C',10,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[iM,mM])),Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[iM,mM,hM]))]))),BO);nO=new vO('OUT_R_B',11,new Er(Vsb(kM,Bv(tv(Gz,1),uyb,41,0,[iM,lM,hM]))),BO);fO=new vO('IN_T_L',12,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[nM,gM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[nM,gM,hM]))]))),BO);eO=new vO('IN_T_C',13,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[nM,fM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[nM,fM,hM]))]))),AO);gO=new vO('IN_T_R',14,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[nM,iM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[nM,iM,hM]))]))),CO);cO=new vO('IN_C_L',15,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,gM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,gM,hM]))]))),BO);bO=new vO('IN_C_C',16,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,fM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,fM,hM]))]))),AO);dO=new vO('IN_C_R',17,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,iM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[mM,iM,hM]))]))),CO);_N=new vO('IN_B_L',18,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[lM,gM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[lM,gM,hM]))]))),BO);$N=new vO('IN_B_C',19,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[lM,fM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[lM,fM,hM]))]))),AO);aO=new vO('IN_B_R',20,new gr(Ti(Bv(tv(UF,1),syb,1,4,[Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[lM,iM])),Vsb(jM,Bv(tv(Gz,1),uyb,41,0,[lM,iM,hM]))]))),CO);tO=new vO(szb,21,(null,Fi),null)}
function lab(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,ab,bb,cb,db,eb,fb,gb,hb,ib;$=0;for(G=0,J=b.length;G<J;++G){D=b[G];if(LM(Wv(rJ(D,(eM(),TL)),28))){for(S=new Tob(D.f);S.a<S.c.c.length;){R=Wv(Rob(S),7);U=0;for(h=new Tob(R.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);D.d!=g.d.f.d&&++U}U>0&&(a.a[R.k]=$++)}}else{L=0;for(S=new Tob(D.f);S.a<S.c.c.length;){R=Wv(Rob(S),7);for(h=new Tob(R.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);D.d!=g.d.f.d&&++L}a.a[R.k]=$}L>0&&++$}}eb=0;for(H=0,K=c.length;H<K;++H){D=c[H];if(LM(Wv(rJ(D,(eM(),TL)),28))){M=0;for(S=new Tob(D.f);S.a<S.c.c.length;){R=Wv(Rob(S),7);if(R.g==(sN(),$M)){for(h=new Tob(R.b);h.a<h.c.c.length;){g=Wv(Rob(h),12);if(D.d!=g.c.f.d){++M;break}}}else{break}}O=0;V=new Fnb(D.f,D.f.c.length);while(V.b>0){R=(Bxb(V.b>0),Wv(V.a.sb(V.c=--V.b),7));U=0;for(h=new Tob(R.b);h.a<h.c.c.length;){g=Wv(Rob(h),12);D.d!=g.c.f.d&&++U}if(U>0){if(R.g==(sN(),$M)){a.a[R.k]=eb;++eb}else{a.a[R.k]=eb+M+O;++O}}}eb+=O}else{L=0;for(S=new Tob(D.f);S.a<S.c.c.length;){R=Wv(Rob(S),7);for(h=new Tob(R.b);h.a<h.c.c.length;){g=Wv(Rob(h),12);D.d!=g.c.f.d&&++L}a.a[R.k]=eb}L>0&&++eb}}T=(mp(),new ntb);n=new Wub;for(F=0,I=b.length;F<I;++F){D=b[F];for(cb=new Tob(D.f);cb.a<cb.c.c.length;){bb=Wv(Rob(cb),7);for(h=new Tob(bb.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);gb=g.d;if(D.d!=gb.f.d){ab=Wv(re(Ktb(T.d,bb)),197);fb=Wv(re(Ktb(T.d,gb)),197);if(!ab&&!fb){m=new oab;n.a.db(m,n);vU(m.a,g);vU(m.d,bb);Ltb(T.d,bb,m);vU(m.d,gb);Ltb(T.d,gb,m)}else if(!ab){vU(fb.a,g);vU(fb.d,bb);Ltb(T.d,bb,fb)}else if(!fb){vU(ab.a,g);vU(ab.d,gb);Ltb(T.d,gb,ab)}else if(ab==fb){vU(ab.a,g)}else{vU(ab.a,g);for(Q=new Tob(fb.d);Q.a<Q.c.c.length;){P=Wv(Rob(Q),7);Ltb(T.d,P,ab)}xU(ab.a,fb.a);xU(ab.d,fb.d);n.a.eb(fb)!=null}}}}}o=Wv(Ye(n,xv(tE,{674:1,3:1,5:1,6:1},197,n.a.Y(),0,1)),674);C=b[0].d;Z=c[0].d;for(k=0,l=o.length;k<l;++k){j=o[k];j.e=$;j.f=eb;for(S=new Tob(j.d);S.a<S.c.c.length;){R=Wv(Rob(S),7);W=a.a[R.k];if(R.f.d==C){W<j.e&&(j.e=W);W>j.b&&(j.b=W)}else if(R.f.d==Z){W<j.f&&(j.f=W);W>j.c&&(j.c=W)}}}ipb(o,0,o.length,(hsb(),hsb(),gsb));db=xv(mw,Yyb,26,o.length,12,1);d=xv(mw,Yyb,26,eb+1,12,1);for(q=0;q<o.length;q++){db[q]=o[q].f;d[db[q]]=1}f=0;for(r=0;r<d.length;r++){d[r]==1?(d[r]=f):--f}X=0;for(s=0;s<db.length;s++){db[s]+=d[db[s]];X=Plb(X,db[s]+1)}i=1;while(i<X){i*=2}ib=2*i-1;i-=1;hb=xv(mw,Yyb,26,ib,12,1);e=0;for(A=0;A<db.length;A++){w=db[A]+i;++hb[w];while(w>0){w%2>0&&(e+=hb[w+1]);w=(w-1)/2|0;++hb[w]}}B=xv(sE,syb,156,o.length*2,0,1);for(t=0;t<o.length;t++){B[2*t]=new rab(o[t],o[t].e,o[t].b,(vab(),uab));B[2*t+1]=new rab(o[t],o[t].b,o[t].e,tab)}ipb(B,0,B.length,(null,gsb));N=0;for(u=0;u<B.length;u++){switch(B[u].d.e){case 0:++N;break;case 1:--N;e+=N;}}Y=xv(sE,syb,156,o.length*2,0,1);for(v=0;v<o.length;v++){Y[2*v]=new rab(o[v],o[v].f,o[v].c,(vab(),uab));Y[2*v+1]=new rab(o[v],o[v].c,o[v].f,tab)}ipb(Y,0,Y.length,(null,gsb));N=0;for(p=0;p<Y.length;p++){switch(Y[p].d.e){case 0:++N;break;case 1:--N;e+=N;}}return e}
function eM(){eM=iI;var a,b;mL=new DJ('de.cau.cs.kieler.animate',(xkb(),xkb(),wkb));new DJ('de.cau.cs.kieler.minAnimTime',Elb(400));new DJ('de.cau.cs.kieler.maxAnimTime',Elb(4000));new DJ('de.cau.cs.kieler.animTimeFactor',Elb(100));jL=new DJ('de.cau.cs.kieler.additionalPortSpace',null);qL=new DJ('de.cau.cs.kieler.commentBox',(null,vkb));new CJ('de.cau.cs.kieler.diagramType');tL=new DJ('de.cau.cs.kieler.edgeLabelPlacement',(EK(),DK));vL=new DJ('de.cau.cs.kieler.edgeType',(YK(),WK));xL=new CJ('de.cau.cs.kieler.fontName');yL=new DJ('de.cau.cs.kieler.fontSize',Elb(0));AL=new DJ('de.cau.cs.kieler.hypernode',(null,vkb));CL=new DJ('de.cau.cs.kieler.junctionPoints',new jJ);new DJ('de.cau.cs.kieler.layoutAncestors',(null,vkb));GL=new DJ('de.cau.cs.kieler.margins',new DP);HL=new EJ('de.cau.cs.kieler.minHeight',new llb(0),new llb(0));IL=new EJ('de.cau.cs.kieler.minWidth',new llb(0),new llb(0));KL=new DJ('de.cau.cs.kieler.noLayout',(null,vkb));LL=new CJ('de.cau.cs.kieler.offset');SL=new CJ('de.cau.cs.kieler.klay.layered.portAnchor');UL=new CJ('de.cau.cs.kieler.portIndex');WL=new DJ('de.cau.cs.kieler.portSide',(sN(),qN));new DJ('de.cau.cs.kieler.progressBar',(null,vkb));new DJ('de.cau.cs.kieler.resetConfig',(null,wkb));new DJ('de.cau.cs.kieler.scaleFactor',new llb(1));dM=new DJ('de.cau.cs.kieler.thickness',new llb(1));new DJ('de.cau.cs.kieler.zoomToFit',(null,vkb));kL=new CJ('de.cau.cs.kieler.algorithm');lL=new DJ('de.cau.cs.kieler.alignment',(iK(),cK));nL=new DJ('de.cau.cs.kieler.aspectRatio',new llb(0));oL=new CJ('de.cau.cs.kieler.bendPoints');pL=new DJ('de.cau.cs.kieler.borderSpacing',new llb(-1));rL=new DJ(uzb,(null,vkb));sL=new DJ('de.cau.cs.kieler.direction',(sK(),qK));uL=new DJ('de.cau.cs.kieler.edgeRouting',(NK(),MK));wL=new DJ('de.cau.cs.kieler.expandNodes',(null,vkb));zL=new DJ('de.cau.cs.kieler.hierarchyHandling',(eL(),cL));BL=new DJ('de.cau.cs.kieler.interactive',(null,vkb));DL=new EJ('de.cau.cs.kieler.labelSpacing',new llb(3),new llb(0));EL=new DJ('de.cau.cs.kieler.layoutHierarchy',(null,vkb));JL=new DJ('de.cau.cs.kieler.nodeLabelPlacement',(oM(),b=Wv(Hkb(Gz),11),new atb(b,Wv(exb(b,b.length),11),0)));TL=new DJ('de.cau.cs.kieler.portConstraints',(KM(),JM));VL=new DJ('de.cau.cs.kieler.portLabelPlacement',(UM(),TM));XL=new EJ('de.cau.cs.kieler.portSpacing',new llb(-1),new llb(0));NL=new DJ('de.cau.cs.kieler.portAlignment',(zM(),xM));PL=new DJ('de.cau.cs.kieler.portAlignment.north',yM);QL=new DJ('de.cau.cs.kieler.portAlignment.south',yM);RL=new DJ('de.cau.cs.kieler.portAlignment.west',yM);OL=new DJ('de.cau.cs.kieler.portAlignment.east',yM);YL=new CJ('de.cau.cs.kieler.position');ZL=new CJ('de.cau.cs.kieler.priority');new CJ(vzb);$L=new DJ('de.cau.cs.kieler.selfLoopInside',(null,vkb));_L=new CJ('de.cau.cs.kieler.separateConnComp');aM=new DJ('de.cau.cs.kieler.sizeConstraint',(DN(),a=Wv(Hkb(Lz),11),new atb(a,Wv(exb(a,a.length),11),0)));bM=new DJ('de.cau.cs.kieler.sizeOptions',Vsb((MN(),KN),Bv(tv(Mz,1),uyb,139,0,[IN])));cM=new EJ('de.cau.cs.kieler.spacing',new llb(-1),new llb(0));FL=new DJ('de.cau.cs.kieler.layoutPartitions',(null,vkb));ML=new CJ('de.cau.cs.kieler.partition')}
function wQ(b,c,d,e){tQ();var f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;if(!e){if((!b.n?(ypb(),ypb(),wpb):b.n).R(new xQ(c))){return}}if(Wv(rQ.a,18).kb(c)){if(!d.lc()){throw new _J(Pzb+c+Qzb+d+').')}o=Wv(Wv(rQ.b,57).cb(c),79);p=d.lc().a;sJ(b,o,p);return}else if(Wv(oQ.a,18).kb(c)){try{if(!d.jc()){throw new Xlb}o=Wv(Wv(oQ.b,57).cb(c),79);s=Elb(dlb((bmb(),''+d.jc().a)));sJ(b,o,s);return}catch(a){a=OH(a);if(aw(a,130)){throw new _J("Invalid integer format for property '"+c+Qzb+d+').')}else throw NH(a)}}else if(Wv(kQ.a,18).kb(c)){if(!d.ic()){throw new _J(Pzb+c+Qzb+d+').')}o=Wv(Wv(kQ.b,57).cb(c),79);s=(xkb(),d.ic().a?wkb:vkb);sJ(b,o,s);return}else if(Wv(nQ.a,18).kb(c)){if(!d.jc()){throw new _J("Invalid float format for property '"+c+Qzb+d+').')}o=Wv(Wv(nQ.b,57).cb(c),79);s=new klb(d.jc().a);sJ(b,o,s);return}else if(Wv(mQ.a,18).kb(c)){if(!d.lc()){throw new _J(Rzb+c+Qzb+d+').')}l=d.lc().a;m=null;try{vQ((eM(),WL),c)?(m=(sN(),Wv(Gc((yN(),xN),l),32))):vQ(lL,c)?(m=(iK(),Wv(Gc((mK(),lK),l),103))):vQ(sL,c)?(m=(sK(),Wv(Gc((zK(),yK),l),59))):vQ(uL,c)?(m=(NK(),Wv(Gc((RK(),QK),l),122))):vQ(zL,c)?(m=(eL(),Wv(Gc((iL(),hL),l),166))):vQ(NL,c)||vQ(OL,c)||vQ(PL,c)||vQ(QL,c)||vQ(RL,c)?(m=(zM(),Wv(Gc((DM(),CM),l),100))):vQ(TL,c)?(m=(KM(),Wv(Gc((QM(),PM),l),28))):vQ(VL,c)?(m=(UM(),Wv(Gc((YM(),XM),l),149))):vQ(vL,c)?(m=(YK(),Wv(Gc((aL(),_K),l),133))):vQ(tL,c)?(m=(EK(),Wv(Gc((IK(),HK),l),107))):vQ((Mjb(),ljb),c)?(m=(Z7(),Wv(Gc((c8(),b8),l),193))):vQ(zjb,c)?(m=(x8(),Wv(Gc((C8(),B8),l),173))):vQ(ojb,c)?(m=(Pgb(),Wv(Gc((Ugb(),Tgb),l),115))):vQ(hjb,c)?(m=(lcb(),Wv(Gc((pcb(),ocb),l),194))):vQ(kjb,c)?(m=(p9(),Wv(Gc((u9(),t9),l),192))):vQ(Bjb,c)?(m=(I1(),Wv(Gc((M1(),L1),l),109))):vQ(Ajb,c)?(m=(kbb(),Wv(Gc((pbb(),obb),l),141))):vQ(Fjb,c)?(m=(g4(),Wv(Gc((k4(),j4),l),125))):vQ(Gjb,c)?(m=(X3(),Wv(Gc((_3(),$3),l),175))):vQ(sjb,c)?(m=(_gb(),Wv(Gc((dhb(),chb),l),124))):vQ(tjb,c)?(m=(zhb(),Wv(Gc((Dhb(),Chb),l),110))):vQ(vjb,c)?(m=(Xib(),Wv(Gc((_ib(),$ib),l),85))):vQ(Jjb,c)?(m=(Qjb(),Wv(Gc((Ujb(),Tjb),l),153))):vQ(Ljb,c)?(m=(ckb(),Wv(Gc((gkb(),fkb),l),172))):vQ(ujb,c)&&(m=(Mhb(),Wv(Gc((Qhb(),Phb),l),174)))}catch(a){a=OH(a);if(aw(a,54)){throw new _J(Rzb+c+Qzb+d+').')}else throw NH(a)}o=Wv(Wv(mQ.b,57).cb(c),79);sJ(b,o,m);return}else if(Wv(lQ.a,18).kb(c)){if(!d.lc()){throw new _J(Rzb+c+Qzb+d+').')}k=d.lc().a;q=null;j=fmb(k,'[\\[\\]\\s,]+');for(h=0,i=j.length;h<i;++h){g=j[h];if(pmb(hmb(g))==0){continue}if(vQ((eM(),JL),c)){!q&&(q=(f=Wv(Hkb(Gz),11),new atb(f,Wv(exb(f,f.length),11),0)));Wsb(q,(oM(),Wv(Gc((sM(),rM),g),41)))}else if(vQ(aM,c)){!q&&(q=(f=Wv(Hkb(Lz),11),new atb(f,Wv(exb(f,f.length),11),0)));Wsb(q,(DN(),Wv(Gc((HN(),GN),g),150)))}else if(vQ(bM,c)){!q&&(q=(f=Wv(Hkb(Mz),11),new atb(f,Wv(exb(f,f.length),11),0)));Wsb(q,(MN(),Wv(Gc((QN(),PN),g),139)))}else if(vQ((Mjb(),jjb),c)){!q&&(q=(f=Wv(Hkb(iF),11),new atb(f,Wv(exb(f,f.length),11),0)));Wsb(q,(zgb(),Wv(Gc((Dgb(),Cgb),g),123)))}}o=Wv(Wv(lQ.b,57).cb(c),79);sJ(b,o,q);return}else if(Wv(qQ.a,18).kb(c)){if(!d.lc()){throw new _J("Invalid _other_ format for property '"+c+Qzb+d+').')}if(vQ((eM(),YL),c)||vQ(SL,c)){try{r=new FI;AI(r,d.lc().a);o=Wv(Wv(qQ.b,57).cb(c),79);sJ(b,o,r);return}catch(a){a=OH(a);if(aw(a,29)){throw new _J("Invalid KVector format for property '"+c+"' "+d+'.')}else throw NH(a)}}else if(vQ(oL,c)||vQ(CL,c)){try{t=new jJ;iJ(t,d.lc().a);o=Wv(Wv(qQ.b,57).cb(c),79);sJ(b,o,t);return}catch(a){a=OH(a);if(aw(a,29)){throw new _J("Invalid KVectorChain format for property '"+c+"' "+d+'.')}else throw NH(a)}}else if(vQ(GL,c)||vQ(jL,c)){try{n=new DP;tP(n,d.lc().a);o=Wv(Wv(qQ.b,57).cb(c),79);sJ(b,o,n);return}catch(a){a=OH(a);if(aw(a,29)){throw new _J("Invalid Margins format for property '"+c+"' "+d+'.')}else throw NH(a)}}}else if(Wv(pQ.a,18).kb(c)){return}throw new _J("Unsupported layout option '"+c+Qzb+d+').')}
var Sxb='object',Txb={3:1,8:1,5:1,6:1},Uxb={3:1,46:1},Vxb={3:1,54:1,46:1},Wxb='null',Xxb='anonymous',Yxb='Unknown',Zxb='function',$xb=2147483647,_xb={181:1,3:1,54:1,46:1},ayb=65536,byb=65535,cyb={3:1,54:1,29:1,46:1},dyb='For input string: "',eyb=-2147483648,fyb={56:1},gyb={23:1,145:1,185:1},hyb={3:1,5:1},iyb='Invalid UTF8 sequence',jyb='fromIndex: ',kyb='java.lang',lyb='com.google.gwt.core.client',myb='com.google.gwt.core.client.impl',nyb='java.io',oyb='java.nio.charset',pyb='javaemul.internal',qyb='com.google.common.base',ryb='%s (%s) must not be negative',syb={3:1,5:1,6:1},tyb='negative size: ',uyb={3:1,8:1,5:1,11:1,6:1},vyb={68:1,136:1,3:1,23:1,17:1},wyb={108:1,35:1},xyb='com.google.common.collect',yyb={108:1,35:1,96:1},zyb={144:1,3:1},Ayb={35:1},Byb={57:1},Cyb='java.util',Dyb={22:1,19:1},Eyb={22:1,19:1,18:1},Fyb={22:1,19:1,20:1},Gyb={22:1,19:1,20:1,63:1},Hyb={35:1,96:1},Iyb={22:1,19:1,18:1,137:1},Jyb={21:1},Kyb='AbstractMapEntry',Lyb={207:1,22:1,19:1},Myb={159:1,3:1,23:1,17:1},Nyb=1073741824,Oyb={22:1},Pyb={3:1,22:1,19:1},Qyb={87:1,3:1,22:1,19:1,20:1,63:1},Ryb={3:1,57:1},Syb={3:1,22:1,19:1,18:1},Tyb={64:1},Uyb='arraySize',Vyb='initialArraySize',Wyb={64:1,188:1,3:1,23:1,17:1},Xyb='occurrences',Yyb={52:1,3:1,5:1},Zyb={205:1,3:1,23:1,17:1},$yb=1.0E-4,_yb='com.google.gwt.json.client',azb=4194303,bzb=1048575,czb=4194304,dzb=17592186044416,ezb=-17592186044416,fzb='([{"\' \t\r\n',gzb=')]}"\' \t\r\n',hzb='The given string contains parts that cannot be parsed as numbers.',izb='de.cau.cs.kieler.core.math',jzb=-1.7976931348623157E308,kzb='de.cau.cs.kieler.core.properties',lzb={79:1,23:1},mzb='de.cau.cs.kieler.core.util',nzb='de.cau.cs.kieler.kiml',ozb='LEFT',pzb='RIGHT',qzb='CENTER',rzb='de.cau.cs.kieler.kiml.options',szb='UNDEFINED',tzb='NONE',uzb='de.cau.cs.kieler.debugMode',vzb='de.cau.cs.kieler.randomSeed',wzb='de.cau.cs.kieler.kiml.util.nodespacing',xzb='de.cau.cs.kieler.kiml.util.labelspacing',yzb='portRatioOrPosition',zzb='NodeMarginCalculator',Azb='bottom',Bzb={286:1,121:1,3:1,5:1},Czb='undefined',Dzb='text',Ezb='stacktrace',Fzb={34:1,3:1,8:1,5:1,6:1},Gzb='properties',Hzb='bendPoints',Izb='junctionPoints',Jzb='width',Kzb='height',Lzb='padding',Mzb='children',Nzb={38:1,39:1,42:1,51:1,71:1,3:1,8:1,5:1,6:1},Ozb='de.cau.cs.kieler.klay.gwt.client.layout',Pzb="Invalid boolean format for property '",Qzb="' (",Rzb="Invalid enum format for property '",Szb='de.cau.cs.kieler.klay.layered',Tzb='Layered layout',Uzb=Infinity,Vzb=-Infinity,Wzb='de.cau.cs.kieler.klay.layered.compaction.components',Xzb='de.cau.cs.kieler.klay.layered.compaction.oned',Yzb=' instance has been finished already.',Zzb='de.cau.cs.kieler.klay.layered.compaction.oned.algs',$zb='de.cau.cs.kieler.klay.layered.compaction.recthull',_zb={68:1},aAb='de.cau.cs.kieler.klay.layered.components',bAb={3:1,5:1,22:1,13:1,19:1,20:1,63:1},cAb=1.600000023841858,dAb=0.001,eAb={31:1},fAb='de.cau.cs.kieler.klay.layered.compound',gAb={38:1,39:1,47:1,42:1,3:1,8:1,5:1,6:1},hAb='de.cau.cs.kieler.klay.layered.graph',iAb='Port side is undefined',jAb='de.cau.cs.kieler.klay.layered.intermediate',kAb='Big nodes pre-processing',lAb=3.4028234663852886E38,mAb={38:1,39:1,42:1,346:1,71:1,3:1,8:1,5:1,6:1},nAb="Node '",oAb="' has its layer constraint set to FIRST or FIRST_SEPARATE, but has ",pAb='at least one incoming edge. Connections between nodes with these ',qAb='layer constraints are not supported.',rAb=1.7976931348623157E308,sAb='Odd port side processing',tAb={250:1,3:1,5:1},uAb=1.0E-8,vAb='de.cau.cs.kieler.klay.layered.intermediate.compaction',wAb='de.cau.cs.kieler.klay.layered.intermediate.greedyswitch',xAb={227:1,3:1,5:1},yAb='de.cau.cs.kieler.klay.layered.networksimplex',zAb='INTERACTIVE',AAb='de.cau.cs.kieler.klay.layered.p1cycles',BAb={106:1,31:1},CAb='de.cau.cs.kieler.klay.layered.p2layers',DAb='NETWORK_SIMPLEX',EAb='de.cau.cs.kieler.klay.layered.p3order',FAb=5.9604644775390625E-8,GAb='Port type is undefined',HAb=0.30000001192092896,IAb=0.699999988079071,JAb=0.8999999761581421,KAb='de.cau.cs.kieler.klay.layered.p3order.constraints',LAb='de.cau.cs.kieler.klay.layered.p3order.counting',MAb='de.cau.cs.kieler.klay.layered.p4nodes',NAb={625:1,3:1,5:1,6:1},OAb='de.cau.cs.kieler.klay.layered.p4nodes.bk',PAb='de.cau.cs.kieler.klay.layered.p5edges',QAb='de.cau.cs.kieler.klay.layered.p5edges.splines',RAb=1.0E-6,SAb=-1.0E-6,TAb='The list of vectors may not be empty.',UAb=0.09999999999999998,VAb='de.cau.cs.kieler.klay.layered.properties',WAb='_gwt_modCount',XAb={3:1,22:1,19:1,20:1,63:1},YAb={3:1,5:1,57:1},ZAb={3:1,5:1,22:1,19:1,50:1,18:1},$Ab='delete',_Ab=15525485,aBb=16777216,bBb=16777215,cBb={3:1,5:1,22:1,19:1,20:1,63:1},dBb={3:1,23:1,17:1,138:1};var _,fI,aI,LH=-1;gI();hI(1,null,{},pb);_.t=function qb(a){return this===a};_.u=function sb(){return this.$c};_.v=function ub(){return txb(this)};_.w=function wb(){return ob(this)};_.toString=function(){return this.w()};hI(46,1,Uxb);_.bc=function ct(){return this.f};_.w=function dt(){var a,b;return a=Ikb(this.$c),b=this.bc(),b!=null?a+': '+b:a};hI(54,46,Vxb);hI(72,54,Vxb,gt);hI(164,72,{164:1,3:1,54:1,46:1},kt);_.bc=function nt(){jt(this);return this.c};_.cc=function ot(){return gw(this.b)===gw(ht)?null:this.b};var ht;var Mt;hI(642,1,{});hI(356,642,{},Tt);_.dc=function Ut(a,b){var c={},k;var d=[];a.__gwt$backingJsError={'fnStack':d};var e=arguments.callee.caller;while(e){var f=(Nt(),e.name||(e.name=Rt(e.toString())));d.push(f);var g=':'+f;var h=c[g];if(h){var i,j;for(i=0,j=h.length;i<j;i++){if(h[i]===e){return}}}(h||(c[g]=[])).push(e);e=e.caller}};_.ec=function Vt(a){var b,c,d,e,f;d=(Nt(),f=a.__gwt$backingJsError,f&&f.fnStack?f.fnStack:[]);c=d.length;e=xv(WF,Txb,146,c,0,1);for(b=0;b<c;b++){e[b]=new Zlb(d[b],null,-1)}return e};hI(643,642,{});_.dc=function Yt(c,d){function e(b){if(!('stack' in b)){try{throw b}catch(a){}}return b}
var f;typeof d=='string'?(f=e(new Error(d.replace('\n',' ')))):d&&typeof d==Sxb&&'stack' in d?(f=d):(f=e(new Error));c.__gwt$backingJsError=f};_.fc=function Zt(a,b,c,d){return new Zlb(b,a+'@'+d,c<0?-1:c)};_.ec=function $t(a){var b,c,d,e,f,g,h;e=(Nt(),h=a.__gwt$backingJsError,h&&h.stack?h.stack.split('\n'):[]);f=xv(WF,Txb,146,0,0,1);b=0;d=e.length;if(d==0){return f}g=Xt(this,e[0]);emb(g.d,Xxb)||(f[b++]=g);for(c=1;c<d;c++){f[b++]=Xt(this,e[c])}return f};hI(357,643,{},_t);_.fc=function au(a,b,c,d){return new Zlb(b,a,-1)};var Sv,Tv,Uv;hI(181,54,_xb);hI(351,181,_xb,ikb);hI(288,1,{},Kkb);_.Oc=function Lkb(a){var b;b=new Kkb;b.g=4;a>1?(b.c=Skb(this,a-1)):(b.c=this);return b};_.Pc=function Rkb(){Gkb(this);return this.b};_.Qc=function Tkb(){return Ikb(this)};_.Rc=function Vkb(){return Jkb(this)};_.Sc=function Xkb(){return (this.g&4)!=0};_.Tc=function Ykb(){return (this.g&1)!=0};_.w=function _kb(){return ((this.g&2)!=0?'interface ':(this.g&1)!=0?'':'class ')+(Gkb(this),this.n)};_.g=0;var Fkb=1;hI(119,72,{3:1,119:1,54:1,46:1},alb);hI(29,72,cyb,rlb,slb);hI(95,72,Vxb,nkb,okb);hI(231,1,{3:1,231:1});var blb;hI(24,231,{3:1,23:1,24:1,231:1},wlb);_.F=function ylb(a){return vlb(this,Wv(a,24))};_.t=function zlb(a){return aw(a,24)&&Wv(a,24).a==this.a};_.v=function Alb(){return this.a};_.w=function Clb(){return Dlb(this.a)};_.a=0;Uv={3:1,345:1,23:1,2:1};hI(350,1,fyb,smb);_.$b=function tmb(a,b){return rmb($v(a),$v(b))};hI(257,95,Vxb,Cmb);hI(145,1,{23:1,145:1});_.F=function Kmb(a){return Jmb(this,Wv(a,145))};_.t=function Lmb(a){var b;if(a===this){return true}if(!aw(a,145)){return false}b=Wv(a,145);return emb(this.a,b.a)};_.v=function Mmb(){return Pxb(this.a)};_.w=function Nmb(){return this.a};hI(358,29,cyb,Omb);hI(256,29,{3:1,54:1,29:1,46:1,256:1},Pmb);hI(185,145,gyb);var jxb,kxb,lxb;hI(289,185,gyb,oxb);_.Zc=function pxb(a,b,c){var d,e;d=xv(jw,hyb,26,c,12,1);for(e=0;e<c;++e){d[e]=a[b+e]&255&byb}return d};hI(355,185,gyb,qxb);_.Zc=function rxb(a,b,c){var d,e,f,g,h,i,j,k;f=0;for(j=0;j<c;){++f;e=a[b+j];if((e&192)==128){throw new slb(iyb)}else if((e&128)==0){++j}else if((e&224)==192){j+=2}else if((e&240)==224){j+=3}else if((e&248)==240){j+=4}else{throw new slb(iyb)}if(j>c){throw new okb(iyb)}}g=xv(jw,hyb,26,f,12,1);k=0;h=0;for(i=0;i<c;){e=a[b+i++];if((e&128)==0){h=1;e&=127}else if((e&224)==192){h=2;e&=31}else if((e&240)==224){h=3;e&=15}else if((e&248)==240){h=4;e&=7}else if((e&252)==248){h=5;e&=3}while(--h>0){d=a[b+i++];if((d&192)!=128){throw new slb('Invalid UTF8 sequence at '+(b+i-1)+', byte='+(d>>>0).toString(16))}e=e<<6|d&63}k+=Ekb(e,g,k)}return g};var UF=Nkb(kyb,'Object',1);var _F=Nkb(kyb,'Throwable',46);var KF=Nkb(kyb,'Exception',54);var VF=Nkb(kyb,'RuntimeException',72);var Zy=Nkb(lyb,'JavaScriptException',164);var ez=Nkb(myb,'StackTraceCreator/Collector',642);var bz=Nkb(myb,'StackTraceCreator/CollectorLegacy',356);var dz=Nkb(myb,'StackTraceCreator/CollectorModern',643);var cz=Nkb(myb,'StackTraceCreator/CollectorModernNoSourceMap',357);var wF=Nkb(nyb,'IOException',181);var zF=Nkb(nyb,'UnsupportedEncodingException',351);var GF=Nkb(kyb,'Class',288);var FF=Nkb(kyb,'ClassCastException',119);var MF=Nkb(kyb,'IllegalArgumentException',29);var OF=Nkb(kyb,'IndexOutOfBoundsException',95);var TF=Nkb(kyb,'Number',231);var PF=Nkb(kyb,'Integer',24);var $F=Nkb(kyb,'String',2);var XF=Nkb(kyb,'String/1',350);var ZF=Nkb(kyb,'StringIndexOutOfBoundsException',257);var bG=Nkb(oyb,'Charset',145);var cG=Nkb(oyb,'IllegalCharsetNameException',358);var dG=Nkb(oyb,'UnsupportedCharsetException',256);var JH=Nkb(pyb,'EmulatedCharset',185);var HH=Nkb(pyb,'EmulatedCharset/LatinCharset',289);var IH=Nkb(pyb,'EmulatedCharset/UtfCharset',355);hI(669,1,{3:1});var sw=Nkb(qyb,'Optional',669);hI(601,669,{3:1},Ab);_.t=function Bb(a){return a===this};_.v=function Cb(){return 2040732332};_.w=function Db(){return 'Optional.absent()'};_.A=function Eb(a){_b(a);return zb(),yb};var yb;var nw=Nkb(qyb,'Absent',601);var ow=Pkb(qyb,'Function');hI(208,1,{},Kb);_.C=function Lb(a){return Ib(a)};var rw=Nkb(qyb,'Joiner',208);hI(363,208,{},Nb);_.C=function Ob(a){return Mb(this,a)};var pw=Nkb(qyb,'Joiner/1',363);hI(362,1,{},Rb);var qw=Nkb(qyb,'Joiner/MapJoiner',362);var tw=Pkb(qyb,'Predicate');var gc;hI(244,1,{68:1,244:1,3:1},ic);_.D=function jc(a){var b;for(b=0;b<this.a.a.length;b++){if(!Wv(mpb(this.a,b),68).D(a)){return false}}return true};_.t=function kc(a){var b;if(aw(a,244)){b=Wv(a,244);return cn(this.a,b.a)}return false};_.v=function lc(){return Bpb(this.a)+306654252};_.w=function mc(){return 'Predicates.and('+Hb((hc(),gc),new wnb(this.a))+')'};var uw=Nkb(qyb,'Predicates/AndPredicate',244);hI(246,1,{68:1,246:1,3:1},nc);_.D=function oc(b){try{return this.a.kb(b)}catch(a){a=OH(a);if(aw(a,76)){return false}else if(aw(a,119)){return false}else throw NH(a)}};_.t=function pc(a){var b;if(aw(a,246)){b=Wv(a,246);return this.a.t(b.a)}return false};_.v=function qc(){return this.a.v()};_.w=function rc(){return 'Predicates.in('+this.a+')'};var vw=Nkb(qyb,'Predicates/InPredicate',246);hI(245,1,{68:1,245:1,3:1},sc);_.D=function tc(a){return rb(this.a,a)};_.t=function uc(a){var b;if(aw(a,245)){b=Wv(a,245);return rb(this.a,b.a)}return false};_.v=function vc(){return vb(this.a)};_.w=function wc(){return 'Predicates.equalTo('+this.a+')'};var ww=Nkb(qyb,'Predicates/IsEqualToPredicate',245);hI(17,1,{3:1,23:1,17:1});_.F=function Bc(a){return xc(this,Wv(a,17))};_.t=function Dc(a){return this===a};_.v=function Ec(){return txb(this)};_.w=function Fc(){return zc(this)};_.e=0;var IF=Nkb(kyb,'Enum',17);hI(136,17,vyb);var Hc,Ic,Jc,Kc;var Bw=Okb(qyb,'Predicates/ObjectPredicate',136,IF,Nc);hI(591,136,vyb,Oc);_.D=function Pc(a){return true};_.w=function Qc(){return 'Predicates.alwaysTrue()'};var xw=Okb(qyb,'Predicates/ObjectPredicate/1',591,Bw,null);hI(592,136,vyb,Rc);_.D=function Sc(a){return false};_.w=function Tc(){return 'Predicates.alwaysFalse()'};var yw=Okb(qyb,'Predicates/ObjectPredicate/2',592,Bw,null);hI(593,136,vyb,Uc);_.D=function Vc(a){return a==null};_.w=function Wc(){return 'Predicates.isNull()'};var zw=Okb(qyb,'Predicates/ObjectPredicate/3',593,Bw,null);hI(594,136,vyb,Xc);_.D=function Yc(a){return a!=null};_.w=function Zc(){return 'Predicates.notNull()'};var Aw=Okb(qyb,'Predicates/ObjectPredicate/4',594,Bw,null);hI(177,669,{177:1,3:1},$c);_.t=function _c(a){var b;if(aw(a,177)){b=Wv(a,177);return rb(this.a,b.a)}return false};_.v=function ad(){return 1502476572+vb(this.a)};_.w=function bd(){return 'Optional.of('+this.a+')'};_.A=function cd(a){return new $c(ac(a.B(this.a),'the Function passed to Optional.transform() must not return null.'))};var Cw=Nkb(qyb,'Present',177);hI(108,1,wyb);_.I=function ed(){dd()};var Xy=Nkb(xyb,'UnmodifiableIterator',108);hI(651,108,yyb);_.J=function fd(a){throw new Hmb};_.O=function gd(a){throw new Hmb};var Yy=Nkb(xyb,'UnmodifiableListIterator',651);hI(378,651,yyb);_.G=function hd(){return this.b<this.c};_.K=function jd(){return this.b>0};_.H=function kd(){if(this.b>=this.c){throw new nvb}return Lk(this,this.b++)};_.L=function ld(){return this.b};_.M=function md(){if(this.b<=0){throw new nvb}return Lk(this,--this.b)};_.N=function nd(){return this.b-1};_.b=0;_.c=0;var Dw=Nkb(xyb,'AbstractIndexedListIterator',378);hI(428,108,wyb);_.G=function rd(){return od(this)};_.H=function sd(){return pd(this)};_.d=1;var Ew=Nkb(xyb,'AbstractIterator',428);hI(653,1,{144:1});_.P=function vd(){var a;return a=this.f,!a?(this.f=this.S()):a};_.T=function wd(){return new Bf(this.P())};_.t=function xd(a){return Mp(this,a)};_.v=function yd(){return this.P().v()};_.V=function zd(){return this.Y()==0};_.W=function Ad(){return ud(this)};_.w=function Bd(){return this.P().w()};var Xw=Nkb(xyb,'AbstractMultimap',653);hI(294,653,zyb);_.Q=function Nd(){Cd(this)};_.R=function Od(a){return Qmb(this.b,a)};_.S=function Pd(){return new Ie(this,this.b)};_.T=function Qd(){return new If(this,this.b)};_.$=function Rd(){return Id(this.Z())};_.U=function Sd(a){return Dd(this,a)};_.X=function Td(a){return Gd(this,a)};_.Y=function Ud(){return this.c};_.c=0;var Uw=Nkb(xyb,'AbstractMapBasedMultimap',294);hI(600,294,zyb);_.Z=function Xd(){return new HU(this.a)};_.$=function Yd(){return Gi(),Gi(),Fi};_.U=function $d(a){return Wv(Dd(this,a),20)};_.X=function _d(a){return Wv(Gd(this,a),20)};_.P=function Wd(){var a;return a=this.f,!a?(this.f=new Ie(this,this.b)):a};_.t=function Zd(a){return Mp(this,a)};var Fw=Nkb(xyb,'AbstractListMultimap',600);hI(388,1,Ayb);_.G=function ae(){return this.b.b||this.d.G()};_.H=function be(){var a;if(!this.d.G()){a=pnb(this.b);a.yb();this.a=Wv(a.zb(),19);this.d=this.a.mb()}return this.d.H()};_.I=function ce(){this.d.I();this.a.V()&&qnb(this.b);--this.c.c};var Kw=Nkb(xyb,'AbstractMapBasedMultimap/Itr',388);hI(389,388,Ayb,de);var Gw=Nkb(xyb,'AbstractMapBasedMultimap/1',389);hI(638,1,Byb);_.Q=function ke(){this.bb().Q()};_._=function le(a){return ee(this,a)};_.R=function me(a){return !!ge(this,a,false)};_.ab=function ne(a){var b,c,d;for(c=this.bb().mb();c.G();){b=Wv(c.H(),21);d=b.zb();if(gw(a)===gw(d)||a!=null&&rb(a,d)){return true}}return false};_.t=function oe(a){return fe(this,a)};_.cb=function pe(a){return re(ge(this,a,false))};_.v=function se(){return Apb(this.bb())};_.V=function te(){return this.Y()==0};_.W=function ue(){return new Snb(this)};_.db=function ve(a,b){throw new Imb('Put not supported on this map')};_.eb=function we(a){return re(ge(this,a,true))};_.Y=function xe(){return this.bb().Y()};_.w=function ye(){return ie(this)};_.fb=function ze(){return new aob(this)};var tG=Nkb(Cyb,'AbstractMap',638);hI(654,638,Byb);_.bb=function Ce(){return Ae(this)};_.W=function De(){var a;a=this.d;return !a?(this.d=new Bf(this)):a};_.fb=function Ee(){return Be(this)};var ny=Nkb(xyb,'Maps/ViewCachingAbstractMap',654);hI(262,654,Byb,Ie);_.cb=function Ne(a){return Fe(this,a)};_.eb=function Qe(a){return Ge(this,a)};_.Q=function Je(){this.a==this.b.b?Cd(this.b):Ml(new xf(this))};_.R=function Ke(a){return qp(this.a,a)};_.hb=function Le(){return new sf(this)};_.gb=function(){return this.hb()};_.t=function Me(a){return this===a||fe(this.a,a)};_.v=function Oe(){return Apb(new inb(this.a))};_.W=function Pe(){return ud(this.b)};_.Y=function Re(){return Zmb(this.a)};_.w=function Se(){return ie(this.a)};var Jw=Nkb(xyb,'AbstractMapBasedMultimap/AsMap',262);hI(640,1,Dyb);_.ib=function $e(a){return Te()};_.jb=function _e(a){return Ue(this,a)};_.Q=function af(){We(this)};_.kb=function bf(a){return Ve(this,a,false)};_.lb=function cf(a){return Xe(this,a)};_.V=function df(){return this.Y()==0};_.nb=function ef(a){return Ve(this,a,true)};_.ob=function ff(){return this.pb(xv(UF,syb,1,this.Y(),4,1))};_.pb=function gf(a){return Ye(this,a)};_.w=function hf(){return Ze(this)};var eG=Nkb(Cyb,'AbstractCollection',640);hI(641,640,Eyb);_.t=function kf(a){return jf(this,a)};_.v=function lf(){return Apb(this)};var zG=Nkb(Cyb,'AbstractSet',641);hI(649,641,Eyb);var Jy=Nkb(xyb,'Sets/ImprovedAbstractSet',649);hI(655,649,Eyb);_.Q=function nf(){this.qb().Q()};_.kb=function of(a){return mf(this,a)};_.V=function pf(){return this.qb().V()};_.nb=function qf(a){var b;if(this.kb(a)){b=Wv(a,21);return this.qb().W().nb(b.yb())}return false};_.Y=function rf(){return this.qb().Y()};var ky=Nkb(xyb,'Maps/EntrySet',655);hI(387,655,Eyb,sf);_.kb=function tf(a){return Qh(new inb(this.a.a),a)};_.mb=function uf(){return new xf(this.a)};_.qb=function vf(){return this.a};_.nb=function wf(a){var b;if(!Qh(new inb(this.a.a),a)){return false}b=Wv(a,21);Hd(this.a.b,b.yb());return true};var Hw=Nkb(xyb,'AbstractMapBasedMultimap/AsMap/AsMapEntries',387);hI(299,1,Ayb,xf);_.H=function zf(){var a;return a=pnb(this.b),this.a=Wv(a.zb(),19),He(this.c,a)};_.G=function yf(){return this.b.b};_.I=function Af(){qnb(this.b);this.c.b.c-=this.a.Y();this.a.Q()};var Iw=Nkb(xyb,'AbstractMapBasedMultimap/AsMap/AsMapIterator',299);hI(260,649,Eyb,Bf);_.Q=function Cf(){this.b.Q()};_.kb=function Df(a){return this.b.R(a)};_.V=function Ef(){return this.b.V()};_.mb=function Ff(){return mp(),Wl(this.b.bb().mb(),(xp(),vp))};_.nb=function Gf(a){if(this.b.R(a)){this.b.eb(a);return true}return false};_.Y=function Hf(){return this.b.Y()};var ly=Nkb(xyb,'Maps/KeySet',260);hI(386,260,Eyb,If);_.Q=function Jf(){var a;Ml((a=this.b.bb().mb(),new Pf(this,a)))};_.lb=function Kf(a){return this.b.W().lb(a)};_.t=function Lf(a){return this===a||this.b.W().t(a)};_.v=function Mf(){return this.b.W().v()};_.mb=function Nf(){var a;return a=this.b.bb().mb(),new Pf(this,a)};_.nb=function Of(a){var b,c;c=0;b=Wv(this.b.eb(a),19);if(b){c=b.Y();b.Q();this.a.c-=c}return c>0};var Mw=Nkb(xyb,'AbstractMapBasedMultimap/KeySet',386);hI(300,1,Ayb,Pf);_.G=function Qf(){return this.c.G()};_.H=function Rf(){this.a=Wv(this.c.H(),21);return this.a.yb()};_.I=function Sf(){var a;ec(!!this.a);a=Wv(this.a.zb(),19);this.c.I();this.b.a.c-=a.Y();a.Q()};var Lw=Nkb(xyb,'AbstractMapBasedMultimap/KeySet/1',300);hI(216,640,Dyb,_f);_.ib=function ag(a){return Tf(this,a)};_.jb=function bg(a){return Uf(this,a)};_.Q=function cg(){Wf(this)};_.kb=function dg(a){return Yf(this),this.d.kb(a)};_.lb=function eg(a){return Yf(this),this.d.lb(a)};_.t=function fg(a){return Xf(this,a)};_.v=function gg(){return Yf(this),this.d.v()};_.mb=function hg(){return Yf(this),new xg(this)};_.nb=function ig(a){return Zf(this,a)};_.Y=function jg(){return Yf(this),this.d.Y()};_.w=function kg(){Yf(this);return xb(this.d)};var Pw=Nkb(xyb,'AbstractMapBasedMultimap/WrappedCollection',216);var sH=Pkb(Cyb,'List');hI(297,216,Fyb,mg);_.rb=function ng(a,b){var c;Yf(this);c=this.d.V();Wv(this.d,20).rb(a,b);++this.a.c;c&&Vf(this)};_.sb=function og(a){Yf(this);return Wv(this.d,20).sb(a)};_.tb=function pg(){Yf(this);return new Cg(this)};_.ub=function qg(a){Yf(this);return new Dg(this,a)};_.vb=function rg(a){var b;Yf(this);b=Wv(this.d,20).vb(a);--this.a.c;$f(this);return b};_.wb=function sg(a,b){Yf(this);return Wv(this.d,20).wb(a,b)};_.xb=function tg(a,b){Yf(this);return Ld(this.a,this.e,Wv(this.d,20).xb(a,b),!this.b?this:this.b)};var Rw=Nkb(xyb,'AbstractMapBasedMultimap/WrappedList',297);hI(385,297,Gyb,ug);var Nw=Nkb(xyb,'AbstractMapBasedMultimap/RandomAccessWrappedList',385);hI(189,1,Ayb,xg);_.G=function zg(){return wg(this),this.b.G()};_.H=function Ag(){return wg(this),this.b.H()};_.I=function Bg(){this.b.I();--this.d.f.c;$f(this.d)};var Ow=Nkb(xyb,'AbstractMapBasedMultimap/WrappedCollection/WrappedIterator',189);hI(298,189,Hyb,Cg,Dg);_.J=function Eg(a){var b;b=lg(this.a)==0;(wg(this),Wv(this.b,96)).J(a);++this.a.a.c;b&&Vf(this.a)};_.K=function Fg(){return (wg(this),Wv(this.b,96)).K()};_.L=function Gg(){return (wg(this),Wv(this.b,96)).L()};_.M=function Hg(){return (wg(this),Wv(this.b,96)).M()};_.N=function Ig(){return (wg(this),Wv(this.b,96)).N()};_.O=function Jg(a){(wg(this),Wv(this.b,96)).O(a)};var Qw=Nkb(xyb,'AbstractMapBasedMultimap/WrappedList/WrappedListIterator',298);hI(295,216,Eyb,Kg);var Sw=Nkb(xyb,'AbstractMapBasedMultimap/WrappedSet',295);hI(296,216,Iyb,Lg);var Tw=Nkb(xyb,'AbstractMapBasedMultimap/WrappedSortedSet',296);hI(668,1,Jyb);_.t=function Mg(a){var b;if(aw(a,21)){b=Wv(a,21);return Tb(this.yb(),b.yb())&&Tb(this.zb(),b.zb())}return false};_.v=function Ng(){var a,b;a=this.yb();b=this.zb();return (a==null?0:vb(a))^(b==null?0:vb(b))};_.Ab=function Og(a){throw new Hmb};_.w=function Pg(){return this.yb()+'='+this.zb()};var Vw=Nkb(xyb,Kyb,668);hI(390,640,Dyb,Qg);_.Q=function Rg(){Cd(this.a)};_.kb=function Sg(a){return td(this.a,a)};_.mb=function Tg(){return new de(this.a)};_.Y=function Ug(){return this.a.c};var Ww=Nkb(xyb,'AbstractMultimap/Values',390);hI(656,640,Lyb);_.ib=function Wg(a){return this.Bb(a,1),true};_.Bb=function Xg(a,b){throw new Hmb};_.jb=function Yg(a){return Eq(this,a)};_.Q=function Zg(){Ml(this.Eb())};_.kb=function $g(a){return this.Cb(a)>0};_.Cb=function _g(a){var b,c;for(c=Vg(this).mb();c.G();){b=Wv(c.H(),83);if(Tb(b.Zb(),a)){return b.Yb()}}return 0};_.gb=function ah(){return new qh(this)};_.bb=function bh(){return Vg(this)};_.t=function dh(a){return Fq(this,a)};_.v=function eh(){return Vg(this).v()};_.V=function fh(){return Vg(this).V()};_.mb=function gh(){return Dq(),new Oq(this,Vg(this).mb())};_.nb=function hh(a){return this.Fb(a,1)>0};_.Fb=function ih(a,b){throw new Hmb};_.Gb=function jh(a,b){var c,d;return Dq(),Mh(b,'count'),c=this.Cb(a),d=b-c,d>0?this.Bb(a,d):d<0&&this.Fb(a,-d),c};_.Hb=function kh(a,b,c){return Gq(this,a,b,c)};_.Y=function lh(){return Hq(this)};_.w=function mh(){return xb(Vg(this))};var Zw=Nkb(xyb,'AbstractMultiset',656);hI(657,649,Eyb);_.Q=function nh(){this.Ib().Q()};_.kb=function oh(a){var b,c;if(aw(a,83)){c=Wv(a,83);if(c.Yb()<=0){return false}b=this.Ib().Cb(c.Zb());return b==c.Yb()}return false};_.nb=function ph(a){var b,c,d,e;if(aw(a,83)){c=Wv(a,83);b=c.Zb();d=c.Yb();if(d!=0){e=this.Ib();return e.Hb(b,d,0)}}return false};var xy=Nkb(xyb,'Multisets/EntrySet',657);hI(396,657,Eyb,qh);_.mb=function rh(){return this.a.Eb()};_.Ib=function sh(){return this.a};_.Y=function th(){return this.a.Db()};var Yw=Nkb(xyb,'AbstractMultiset/EntrySet',396);hI(384,294,zyb);_.Z=function wh(){return new wtb(op(this.a))};_.$=function xh(){return hi(),kr(),jr};_.U=function zh(a){return Wv(Dd(this,a),18)};_.X=function Ah(a){return Wv(Gd(this,a),18)};_.P=function vh(){var a;return a=this.f,!a?(this.f=new Ie(this,this.b)):a};_.t=function yh(a){return Mp(this,a)};var $w=Nkb(xyb,'AbstractSetMultimap',384);hI(342,656,Lyb);var _w=Nkb(xyb,'AbstractSortedMultiset',342);hI(280,600,zyb,Dh);_.a=0;var ax=Nkb(xyb,'ArrayListMultimap',280);hI(159,17,Myb);var Eh,Fh;var dx=Okb(xyb,'BoundType',159,IF,Ih);hI(623,159,Myb,Jh);var bx=Okb(xyb,'BoundType/1',623,dx,null);hI(624,159,Myb,Kh);var cx=Okb(xyb,'BoundType/2',624,dx,null);var Nh;hI(234,1,Oyb);_.w=function Th(){return Vl(this.c.mb())};var fx=Nkb(xyb,'FluentIterable',234);hI(170,234,Oyb,Vh);_.mb=function Wh(){return Uh(this)};var ex=Nkb(xyb,'FluentIterable/2',170);hI(664,1,{});_.w=function Xh(){return xb(irb(this.a.d).b)};var mx=Nkb(xyb,'ForwardingObject',664);hI(665,664,Dyb);_.ib=function Yh(a){return irb(this.a.d),vqb()};_.jb=function Zh(a){return irb(this.a.d),wqb()};_.Q=function $h(){irb(this.a.d);xqb()};_.kb=function _h(a){return Irb(irb(this.a.d),a)};_.lb=function ai(a){return Jrb(irb(this.a.d),a)};_.V=function bi(){return irb(this.a.d).b.V()};_.mb=function ci(){var a;return a=irb(this.a.d).b.mb(),new Trb(a)};_.nb=function di(a){return irb(this.a.d),yqb()};_.Y=function ei(){return irb(this.a.d).b.Y()};_.ob=function fi(){return Krb(irb(this.a.d))};_.pb=function gi(a){return Lrb(irb(this.a.d),a)};var gx=Nkb(xyb,'ForwardingCollection',665);hI(660,640,Pyb);_.mb=function ti(){return this.Kb()};_.ib=function oi(a){return ii()};_.jb=function pi(a){return ji()};_.Q=function qi(){li()};_.kb=function ri(a){return a!=null&&Ve(this,a,false)};_.Jb=function si(){switch(this.Y()){case 0:return Gi(),Gi(),Fi;case 1:return Gi(),new Er(this.Kb().H());default:return new Zq(this,this.ob());}};_.nb=function ui(a){return mi()};var sx=Nkb(xyb,'ImmutableCollection',660);hI(316,660,Pyb,vi);_.mb=function Ai(){return Xl(this.a.mb())};_.kb=function wi(a){return a!=null&&this.a.kb(a)};_.lb=function xi(a){return this.a.lb(a)};_.V=function yi(){return this.a.V()};_.Kb=function zi(){return Xl(this.a.mb())};_.Y=function Bi(){return this.a.Y()};_.ob=function Ci(){return this.a.ob()};_.pb=function Di(a){return this.a.pb(a)};_.w=function Ei(){return xb(this.a)};var hx=Nkb(xyb,'ForwardingImmutableCollection',316);hI(87,660,Qyb);_.mb=function Pi(){return this.Kb()};_.tb=function Qi(){return this.Lb(0)};_.ub=function Si(a){return this.Lb(a)};_.xb=function Xi(a,b){return this.Mb(a,b)};_.rb=function Ji(a,b){throw new Hmb};_.t=function Mi(a){return yo(this,a)};_.v=function Ni(){return zo(this)};_.Kb=function Oi(){return this.Lb(0)};_.Lb=function Ri(a){return Hi(this,a)};_.vb=function Ui(a){throw new Hmb};_.wb=function Vi(a,b){throw new Hmb};_.Mb=function Wi(a,b){var c;return Yi((c=new Mo(this),new Mnb(c,a,b)))};var Fi;var wx=Nkb(xyb,'ImmutableList',87);hI(667,87,Qyb);_.mb=function gj(){return Xl(this.Nb().mb())};_.xb=function jj(a,b){return Yi(this.Nb().xb(a,b))};_.kb=function _i(a){return Zi(this,a)};_.lb=function aj(a){return this.Nb().lb(a)};_.t=function bj(a){return this.Nb().t(a)};_.sb=function cj(a){return $i(this,a)};_.v=function dj(){return this.Nb().v()};_.V=function ej(){return this.Nb().V()};_.Kb=function fj(){return Xl(this.Nb().mb())};_.Y=function hj(){return this.Nb().Y()};_.Mb=function ij(a,b){return Yi(this.Nb().xb(a,b))};_.ob=function kj(){return this.Nb().pb(xv(UF,syb,1,this.Nb().Y(),4,1))};_.pb=function lj(a){return this.Nb().pb(a)};_.w=function mj(){return xb(this.Nb())};var ix=Nkb(xyb,'ForwardingImmutableList',667);hI(524,1,Ryb);_.bb=function wj(){return nj(this)};_.W=function Aj(){return oj(this)};_.fb=function Gj(){return this.Rb()};_.Q=function qj(){throw new Hmb};_.R=function rj(a){return this.cb(a)!=null};_.ab=function sj(a){return this.Rb().kb(a)};_.Pb=function uj(){return new Uk(this)};_.Qb=function vj(){return new Zk(this)};_.t=function xj(a){return pp(this,a)};_.v=function yj(){return nj(this).v()};_.V=function zj(){return this.Y()==0};_.db=function Cj(a,b){return pj()};_.eb=function Dj(a){throw new Hmb};_.w=function Ej(){var a;return mp(),a=umb(Ph(this.Y()),123),Qb(lp,a,nj(this).mb()),a.a+='}',a.a};_.Rb=function Fj(){if(this.g){return this.g}return this.g=this.Qb()};_.e=null;_.f=null;_.g=null;var Cx=Nkb(xyb,'ImmutableMap',524);hI(320,524,Ryb);_.R=function Ij(a){return qp(this.d,a)};_.ab=function Jj(a){return hrb(this.d,a)};_.Ob=function Kj(){return ck(new Vj(this))};_.Pb=function Lj(){return ck(krb(this.d))};_.Qb=function Mj(){return hi(),new vi(lrb(this.d))};_.t=function Nj(a){return jrb(this.d,a)};_.cb=function Oj(a){return a==null?null:rp(this.d,a)};_.v=function Pj(){return this.d.c.v()};_.V=function Qj(){return this.d.c.V()};_.Y=function Rj(){return this.d.c.Y()};_.w=function Sj(){return xb(this.d.c)};var kx=Nkb(xyb,'ForwardingImmutableMap',320);hI(666,665,Eyb);_.t=function Tj(a){return a===this||Drb(irb(this.a.d),a)};_.v=function Uj(){return irb(this.a.d).b.v()};var nx=Nkb(xyb,'ForwardingSet',666);hI(523,666,Eyb,Vj);_.kb=function Wj(b){if(aw(b,21)&&Wv(b,21).yb()==null){return false}try{return Irb(irb(this.a.d),b)}catch(a){a=OH(a);if(aw(a,119)){return false}else throw NH(a)}};_.pb=function Xj(a){var b;b=Lrb(irb(this.a.d),a);irb(this.a.d).b.Y()<b.length&&Av(b,irb(this.a.d).b.Y(),null);return b};var jx=Nkb(xyb,'ForwardingImmutableMap/1',523);hI(663,660,Syb);_.mb=function ak(){return this.Kb()};_.t=function $j(a){return mr(this,a)};_.v=function _j(){return nr(this)};var Fx=Nkb(xyb,'ImmutableSet',663);hI(315,663,Syb);_.mb=function jk(){return Xl(new Nqb(this.a.b.mb()))};_.kb=function ek(a){return a!=null&&Brb(this.a,a)};_.lb=function fk(a){return Crb(this.a,a)};_.v=function gk(){return this.a.b.v()};_.V=function hk(){return this.a.b.V()};_.Kb=function ik(){return Xl(new Nqb(this.a.b.mb()))};_.Y=function kk(){return this.a.b.Y()};_.ob=function lk(){return this.a.b.ob()};_.pb=function mk(a){return Erb(this.a,a)};_.w=function nk(){return xb(this.a.b)};var lx=Nkb(xyb,'ForwardingImmutableSet',315);hI(178,1,{178:1,3:1},sk);_.t=function tk(a){var b;if(aw(a,178)){b=Wv(a,178);return this.a.t(b.a)&&this.b==b.b&&this.c==b.c&&this.d==b.d&&this.f==b.f&&Tb(this.e,b.e)&&Tb(this.g,b.g)}return false};_.v=function uk(){return fpb(Bv(tv(UF,1),syb,1,4,[this.a,this.e,this.d,this.g,this.f]))};_.w=function vk(){return umb(xmb(umb(xmb(umb(ymb(xmb(new zmb,this.a),':'),this.d==(Gh(),Eh)?91:40),this.b?this.e:'-\u221E'),44),this.c?this.g:'\u221E'),this.f==Eh?93:41).a};_.b=false;_.c=false;var ox=Nkb(xyb,'GeneralRange',178);hI(215,384,zyb,xk);_.a=2;var px=Nkb(xyb,'HashMultimap',215);hI(661,87,Qyb);_.kb=function yk(a){return this.Sb().kb(a)};_.V=function zk(){return this.Sb().V()};_.Y=function Ak(){return this.Sb().Y()};var qx=Nkb(xyb,'ImmutableAsList',661);hI(275,320,Ryb);_.Rb=function Ck(){return this.Ub()};_.fb=function Ek(){return this.Ub()};_.Ub=function Dk(){return oj(this.Tb())};var rx=Nkb(xyb,'ImmutableBiMap',275);hI(341,668,{3:1,21:1},Fk);_.yb=function Gk(){return this.a};_.zb=function Hk(){return this.b};_.Ab=function Ik(a){throw new Hmb};var tx=Nkb(xyb,'ImmutableEntry',341);hI(436,315,Syb,Jk);var ux=Nkb(xyb,'ImmutableEnumSet',436);hI(379,378,yyb,Mk);var vx=Nkb(xyb,'ImmutableList/1',379);hI(266,108,wyb,Nk);_.G=function Ok(){return this.a.G()};_.H=function Pk(){return Wv(this.a.H(),21).yb()};var xx=Nkb(xyb,'ImmutableMap/1',266);hI(670,663,Syb);_.mb=function Sk(){var a;return a=nj(this.a).Kb(),new Nk(a)};_.Jb=function Qk(){return new jl(this)};_.Kb=function Rk(){var a;return (a=this.c,!a?(this.c=new jl(this)):a).Kb()};var Ex=Nkb(xyb,'ImmutableSet/Indexed',670);hI(606,670,Syb,Uk);_.mb=function Xk(){var a;return a=nj(this.a).Kb(),new Nk(a)};_.kb=function Vk(a){return this.a.R(a)};_.Kb=function Wk(){var a;return a=nj(this.a).Kb(),new Nk(a)};_.Y=function Yk(){return this.a.Y()};var yx=Nkb(xyb,'ImmutableMapKeySet',606);hI(604,660,Pyb,Zk);_.mb=function bl(){return new dl(this)};_.kb=function $k(a){return a!=null&&(Il(),Il(),Tl(new dl(this),(hc(),a==null?(Lc(),Jc):new sc(a)))!=-1)};_.Jb=function _k(){var a;a=ki(nj(this.a));return new gl(this,a)};_.Kb=function al(){return new dl(this)};_.Y=function cl(){return this.a.Y()};var Bx=Nkb(xyb,'ImmutableMapValues',604);hI(282,108,wyb,dl);_.G=function el(){return this.a.G()};_.H=function fl(){return Wv(this.a.H(),21).zb()};var zx=Nkb(xyb,'ImmutableMapValues/1',282);hI(605,661,Qyb,gl);_.Sb=function hl(){return this.a};_.sb=function il(a){return Wv(this.b.sb(a),21).zb()};var Ax=Nkb(xyb,'ImmutableMapValues/2',605);hI(311,661,Qyb,jl);_.Sb=function kl(){return this.a};_.sb=function ll(a){return Tk(this.a,a)};var Dx=Nkb(xyb,'ImmutableSet/Indexed/1',311);hI(414,234,Oyb,vl);_.mb=function wl(){return Nl(this.a)};_.w=function xl(){return Ze(this.a)+' (cycled)'};var Hx=Nkb(xyb,'Iterables/1',414);hI(105,1,Tyb,yl);_.B=function zl(a){return Wv(a,22).mb()};var Gx=Nkb(xyb,'Iterables/12',105);hI(415,234,Oyb,Bl);_.mb=function Cl(){return Al(this)};var Ix=Nkb(xyb,'Iterables/4',415);hI(416,234,Oyb,El);_.mb=function Fl(){return Dl(this)};var Jx=Nkb(xyb,'Iterables/5',416);var Gl,Hl;hI(424,651,yyb,Yl);_.G=function Zl(){return false};_.K=function $l(){return false};_.H=function _l(){throw new nvb};_.L=function am(){return 0};_.M=function bm(){throw new nvb};_.N=function cm(){return -1};var Lx=Nkb(xyb,'Iterators/1',424);hI(264,108,wyb,dm);_.G=function em(){return !this.a};_.H=function fm(){if(this.a){throw new nvb}this.a=true;return this.b};_.a=false;var Kx=Nkb(xyb,'Iterators/11',264);hI(425,1,Ayb,gm);_.G=function hm(){return false};_.H=function im(){throw new nvb};_.I=function jm(){ec(false)};var Mx=Nkb(xyb,'Iterators/2',425);hI(426,108,wyb,km);_.G=function lm(){return this.a.G()};_.H=function mm(){return this.a.H()};var Nx=Nkb(xyb,'Iterators/3',426);hI(427,1,Ayb,om);_.G=function pm(){return this.a.G()||this.b.mb().G()};_.H=function qm(){return nm(this)};_.I=function rm(){this.a.I()};var Ox=Nkb(xyb,'Iterators/4',427);hI(429,428,wyb,tm);var Px=Nkb(xyb,'Iterators/6',429);hI(261,1,Ayb);_.G=function wm(){return this.b.G()};_.H=function xm(){return um(this)};_.I=function ym(){this.b.I()};var Oy=Nkb(xyb,'TransformedIterator',261);hI(430,261,Ayb,Am);_.Vb=function Bm(a){return zm(this,a)};var Qx=Nkb(xyb,'Iterators/7',430);hI(313,1,Ayb);_.G=function Fm(){return Cm(this)};_.H=function Gm(){return Dm(this)};_.I=function Hm(){ec(!!this.c);this.c.I();this.c=null};var Ay=Nkb(xyb,'MultitransformedIterator',313);hI(90,313,{90:1,35:1},Im);_.Wb=function Jm(a){return Wv(a,35)};var Sx=Nkb(xyb,'Iterators/ConcatenatedIterator',90);hI(314,313,Ayb,Lm);_.Wb=function Mm(a){return Km(Wv(a,35))};var Rx=Nkb(xyb,'Iterators/ConcatenatedIterator/1',314);hI(329,653,zyb,Um);_.U=function $m(a){return new Bn(this,a)};_.X=function an(a){return Sm(this,a)};_.Q=function Wm(){Pm(this)};_.R=function Xm(a){return Qm(this,a)};_.S=function Ym(){return new Pp(this)};_.T=function Zm(){return new Hn(this)};_.V=function _m(){return !this.a};_.Y=function bn(){return this.d};_.c=0;_.d=0;var _x=Nkb(xyb,'LinkedListMultimap',329);hI(647,640,Fyb);_.rb=function en(a,b){throw new Imb('Add not supported on this list')};_.ib=function fn(a){this.rb(this.Y(),a);return true};_.Q=function gn(){this.Xb(0,this.Y())};_.t=function hn(a){return cn(this,a)};_.v=function jn(){return Bpb(this)};_.mb=function kn(){return new wnb(this)};_.tb=function ln(){return this.ub(0)};_.ub=function mn(a){return new Fnb(this,a)};_.vb=function nn(a){throw new Imb('Remove not supported on this list')};_.Xb=function on(a,b){var c,d;d=this.ub(a);for(c=a;c<b;++c){d.H();d.I()}};_.wb=function pn(a,b){throw new Imb('Set not supported on this list')};_.xb=function qn(a,b){return new Mnb(this,a,b)};_.d=0;var lG=Nkb(Cyb,'AbstractList',647);hI(648,647,Fyb);_.rb=function vn(a,b){rn(this,a,b)};_.sb=function wn(a){return tn(this,a)};_.mb=function xn(){return this.ub(0)};_.vb=function yn(a){return un(this,a)};_.wb=function zn(b,c){var d,e;d=this.ub(b);try{e=d.H();d.O(c);return e}catch(a){a=OH(a);if(aw(a,74)){throw new okb("Can't set element "+b)}else throw NH(a)}};var yG=Nkb(Cyb,'AbstractSequentialList',648);hI(276,648,Fyb,Bn);_.ub=function Cn(a){return An(this,a)};_.Y=function Dn(){var a;a=Wv(Smb(this.a.b,this.b),126);return !a?0:a.a};var Vx=Nkb(xyb,'LinkedListMultimap/1',276);hI(330,648,Fyb,En);_.ub=function Fn(a){return new _n(this.a,a)};_.Y=function Gn(){return this.a.d};var Tx=Nkb(xyb,'LinkedListMultimap/1EntriesImpl',330);hI(563,649,Eyb,Hn);_.kb=function In(a){return Qm(this.a,a)};_.mb=function Jn(){return new Nn(this.a)};_.nb=function Kn(a){return !Sm(this.a,a).a.V()};_.Y=function Ln(){return Zmb(this.a.b)};var Ux=Nkb(xyb,'LinkedListMultimap/1KeySetImpl',563);hI(562,1,Ayb,Nn);_.G=function On(){Mn(this);return !!this.c};_.H=function Pn(){Mn(this);Vm(this.c);this.a=this.c;stb(this.d,this.a.a);do{this.c=this.c.b}while(!!this.c&&!stb(this.d,this.c.a));return this.a.a};_.I=function Qn(){Mn(this);ec(!!this.a);Ml(new mo(this.e,this.a.a));this.a=null;this.b=this.e.c};_.b=0;var Wx=Nkb(xyb,'LinkedListMultimap/DistinctKeyIterator',562);hI(126,1,{126:1},Rn);_.a=0;var Xx=Nkb(xyb,'LinkedListMultimap/KeyList',126);hI(560,668,Jyb,Sn);_.yb=function Tn(){return this.a};_.zb=function Un(){return this.f};_.Ab=function Vn(a){var b;b=this.f;this.f=a;return b};var Zx=Nkb(xyb,'LinkedListMultimap/Node',560);hI(561,1,Hyb,_n);_.J=function ao(a){Wv(a,21);Wn()};_.H=function eo(){return Yn(this)};_.M=function go(){return Zn(this)};_.O=function jo(a){Wv(a,21);$n()};_.G=function bo(){Xn(this);return !!this.c};_.K=function co(){Xn(this);return !!this.e};_.L=function fo(){return this.d};_.N=function ho(){return this.d-1};_.I=function io(){Xn(this);ec(!!this.a);if(this.a!=this.c){this.e=this.a.d;--this.d}else{this.c=this.a.b}Tm(this.f,this.a);this.a=null;this.b=this.f.c};_.b=0;_.d=0;var Yx=Nkb(xyb,'LinkedListMultimap/NodeIterator',561);hI(241,1,Hyb,mo,no);_.J=function oo(a){this.e=Nm(this.f,this.b,a,this.c);++this.d;this.a=null};_.G=function po(){return !!this.c};_.K=function qo(){return !!this.e};_.H=function ro(){return ko(this)};_.L=function so(){return this.d};_.M=function to(){return lo(this)};_.N=function uo(){return this.d-1};_.I=function vo(){ec(!!this.a);if(this.a!=this.c){this.e=this.a.e;--this.d}else{this.c=this.a.c}Tm(this.f,this.a);this.a=null};_.O=function wo(a){dc(!!this.a);this.a.f=a};_.d=0;var $x=Nkb(xyb,'LinkedListMultimap/ValueForKeyIterator',241);hI(419,647,Fyb);_.rb=function Go(a,b){this.a.rb(a,b)};_.kb=function Ho(a){return this.a.kb(a)};_.sb=function Io(a){return this.a.sb(a)};_.vb=function Jo(a){return this.a.vb(a)};_.wb=function Ko(a,b){return this.a.wb(a,b)};_.Y=function Lo(){return this.a.Y()};var by=Nkb(xyb,'Lists/AbstractListWrapper',419);hI(420,419,Gyb);var cy=Nkb(xyb,'Lists/RandomAccessListWrapper',420);hI(422,420,Gyb,Mo);_.ub=function No(a){return this.a.ub(a)};var ay=Nkb(xyb,'Lists/1',422);hI(88,647,{88:1,22:1,19:1,20:1},Ro);_.rb=function So(a,b){this.a.rb(Qo(this,a),b)};_.Q=function To(){this.a.Q()};_.sb=function Uo(a){return this.a.sb(Po(this,a))};_.mb=function Vo(){return Oo(this,0)};_.ub=function Wo(a){return Oo(this,a)};_.vb=function Xo(a){return this.a.vb(Po(this,a))};_.Xb=function Yo(a,b){(cc(a,b,this.a.Y()),Fo(this.a.xb(Qo(this,b),Qo(this,a)))).Q()};_.wb=function Zo(a,b){return this.a.wb(Po(this,a),b)};_.Y=function $o(){return this.a.Y()};_.xb=function _o(a,b){return cc(a,b,this.a.Y()),Fo(this.a.xb(Qo(this,b),Qo(this,a)))};var fy=Nkb(xyb,'Lists/ReverseList',88);hI(220,88,{88:1,22:1,19:1,20:1,63:1},ap);var dy=Nkb(xyb,'Lists/RandomAccessReverseList',220);hI(421,1,Hyb,bp);_.J=function cp(a){this.c.J(a);this.c.M();this.a=false};_.G=function dp(){return this.c.K()};_.K=function ep(){return this.c.G()};_.H=function fp(){if(!this.c.K()){throw new nvb}this.a=true;return this.c.M()};_.L=function gp(){return Qo(this.b,this.c.L())};_.M=function hp(){if(!this.c.G()){throw new nvb}this.a=true;return this.c.H()};_.N=function ip(){return Qo(this.b,this.c.L())-1};_.I=function jp(){ec(this.a);this.c.I();this.a=false};_.O=function kp(a){dc(this.a);this.c.O(a)};_.a=false;var ey=Nkb(xyb,'Lists/ReverseList/1',421);var lp;hI(376,261,Ayb,tp);_.Vb=function up(a){return mp(),new Fk(a,aq(this.a,a))};var gy=Nkb(xyb,'Maps/1',376);hI(188,17,Wyb);var vp,wp;var jy=Okb(xyb,'Maps/EntryFunction',188,IF,zp);hI(374,188,Wyb,Ap);_.B=function Bp(a){return Wv(a,21).yb()};var hy=Okb(xyb,'Maps/EntryFunction/1',374,jy,null);hI(375,188,Wyb,Cp);_.B=function Dp(a){return Wv(a,21).zb()};var iy=Okb(xyb,'Maps/EntryFunction/2',375,jy,null);hI(373,640,Dyb,Fp);_.Q=function Gp(){this.a.Q()};_.kb=function Hp(a){return this.a.ab(a)};_.V=function Ip(){return this.a.V()};_.mb=function Jp(){return Ep(this)};_.nb=function Kp(b){var c,d;try{return Ve(this,b,true)}catch(a){a=OH(a);if(aw(a,45)){for(d=this.a.bb().mb();d.G();){c=Wv(d.H(),21);if(Tb(b,c.zb())){this.a.eb(c.yb());return true}}return false}else throw NH(a)}};_.Y=function Lp(){return this.a.Y()};var my=Nkb(xyb,'Maps/Values',373);hI(301,654,Byb,Pp);_.cb=function Tp(a){return this.a.R(a)?this.a.U(a):null};_.eb=function Wp(a){return this.a.R(a)?this.a.X(a):null};_.Q=function Qp(){this.a.Q()};_.R=function Rp(a){return this.a.R(a)};_.hb=function Sp(){return new Yp(this)};_.gb=function(){return this.hb()};_.V=function Up(){return this.a.V()};_.W=function Vp(){return this.a.W()};_.Y=function Xp(){return this.a.W().Y()};var qy=Nkb(xyb,'Multimaps/AsMap',301);hI(393,655,Eyb,Yp);_.mb=function Zp(){return np(this.a.a.W(),new bq(this))};_.qb=function $p(){return this.a};_.nb=function _p(a){var b;if(!mf(this,a)){return false}b=Wv(a,21);Op(this.a,b.yb());return true};var py=Nkb(xyb,'Multimaps/AsMap/EntrySet',393);hI(395,1,Tyb,bq);_.B=function cq(a){return aq(this,a)};var oy=Nkb(xyb,'Multimaps/AsMap/EntrySet/1',395);hI(391,656,Lyb,eq);_.Q=function fq(){Pm(this.a)};_.kb=function gq(a){return Qm(this.a,a)};_.Cb=function hq(a){var b;return b=Wv(rp(Om(this.a),a),19),!b?0:b.Y()};_.gb=function iq(){return new wq(this)};_.Db=function jq(){return Om(this.a).Y()};_.Eb=function kq(){return new nq(Ae(Om(this.a)).mb())};_.mb=function lq(){return dq(this)};_.Fb=function mq(a,b){var c,d,e,f,g;Mh(b,Xyb);if(b==0){return g=Wv(rp(Om(this.a),a),19),!g?0:g.Y()}f=Wv(rp(Om(this.a),a),19);if(!f){return 0}e=f.Y();if(b>=e){f.Q()}else{d=f.mb();for(c=0;c<b;c++){d.H();d.I()}}return e};var uy=Nkb(xyb,'Multimaps/Keys',391);hI(302,261,Ayb,nq);_.Vb=function oq(a){return new tq(Wv(a,21))};var sy=Nkb(xyb,'Multimaps/Keys/1',302);hI(658,1,{83:1});_.t=function qq(a){var b;if(aw(a,83)){b=Wv(a,83);return this.Yb()==b.Yb()&&Tb(this.Zb(),b.Zb())}return false};_.v=function rq(){var a;a=this.Zb();return (a==null?0:vb(a))^this.Yb()};_.w=function sq(){return pq(this)};var wy=Nkb(xyb,'Multisets/AbstractEntry',658);hI(394,658,{83:1},tq);_.Yb=function uq(){return Wv(this.a.zb(),19).Y()};_.Zb=function vq(){return this.a.yb()};var ry=Nkb(xyb,'Multimaps/Keys/1/1',394);hI(392,657,Eyb,wq);_.kb=function xq(a){var b,c;if(aw(a,83)){c=Wv(a,83);b=Wv(Om(this.a.a).cb(c.Zb()),19);return !!b&&b.Y()==c.Yb()}return false};_.V=function yq(){return !this.a.a.a};_.mb=function zq(){return new nq(Ae(Om(this.a.a)).mb())};_.Ib=function Aq(){return this.a};_.nb=function Bq(a){var b,c;if(aw(a,83)){c=Wv(a,83);b=Wv(Om(this.a.a).cb(c.Zb()),19);if(!!b&&b.Y()==c.Yb()){b.Q();return true}}return false};_.Y=function Cq(){return Om(this.a.a).Y()};var ty=Nkb(xyb,'Multimaps/Keys/KeysEntrySet',392);hI(659,1,fyb);var Cy=Nkb(xyb,'Ordering',659);hI(398,659,fyb,Jq);_.$b=function Kq(a,b){return Iq(Wv(a,83),Wv(b,83))};var vy=Nkb(xyb,'Multisets/1',398);hI(397,658,{83:1,3:1},Lq);_.Yb=function Mq(){return this.a};_.Zb=function Nq(){return this.b};_.a=0;var yy=Nkb(xyb,'Multisets/ImmutableEntry',397);hI(303,1,Ayb,Oq);_.G=function Pq(){return this.d>0||this.c.G()};_.H=function Qq(){if(!(this.d>0||this.c.G())){throw new nvb}if(this.d==0){this.b=Wv(this.c.H(),83);this.f=this.d=this.b.Yb()}--this.d;this.a=true;return this.b.Zb()};_.I=function Rq(){ec(this.a);this.f==1?this.c.I():this.e.Fb(this.b.Zb(),1)>0;--this.f;this.a=false};_.a=false;_.d=0;_.f=0;var zy=Nkb(xyb,'Multisets/MultisetIteratorImpl',303);hI(622,659,{3:1,56:1},Vq);_.$b=function Wq(a,b){return Uq(Wv(a,23),Wv(b,23))};_.w=function Xq(){return 'Ordering.natural()'};var Sq;var By=Nkb(xyb,'NaturalOrdering',622);hI(343,661,Qyb,Zq);_.ub=function br(a){return Hi(this.b,a)};_.Sb=function $q(){return this.a};_.sb=function _q(a){return $i(this.b,a)};_.Lb=function ar(a){return Hi(this.b,a)};var Dy=Nkb(xyb,'RegularImmutableAsList',343);hI(559,275,Ryb,er);_.Tb=function fr(){return this.a};var cr;var Ey=Nkb(xyb,'RegularImmutableBiMap',559);hI(53,667,Qyb,gr);_.Nb=function hr(){return this.a};var Fy=Nkb(xyb,'RegularImmutableList',53);hI(321,320,Ryb,ir);var Gy=Nkb(xyb,'RegularImmutableMap',321);hI(265,315,Syb,lr);var jr;var Hy=Nkb(xyb,'RegularImmutableSet',265);hI(650,641,Eyb);var Ky=Nkb(xyb,'Sets/SetView',650);hI(377,650,Eyb,tr);_.kb=function ur(a){return ttb(this.b,a)&&ttb(this.c,a)};_.lb=function vr(a){return Xe(this.b,a)&&Xe(this.c,a)};_.V=function wr(){return sr(this)};_.mb=function xr(){var a;return Pl((a=(new Snb(this.b.a)).a.bb().mb(),new Ynb(a)),this.a)};_.Y=function yr(){var a;return Ul(Pl((a=(new Snb(this.b.a)).a.bb().mb(),new Ynb(a)),this.a))};var Iy=Nkb(xyb,'Sets/2',377);hI(328,275,Ryb,zr,Ar);_.fb=function Dr(){return hi(),new Gr(this.c)};_.Tb=function Br(){var a;a=this.a;return !a?(this.a=new Ar(this.c,this.b,this)):a};_.Ub=function Cr(){return hi(),new Gr(this.c)};var Ly=Nkb(xyb,'SingletonImmutableBiMap',328);hI(127,667,Qyb,Er);_.Nb=function Fr(){return this.a};var My=Nkb(xyb,'SingletonImmutableList',127);hI(135,663,Syb,Gr);_.mb=function Jr(){return Il(),new dm(this.a)};_.kb=function Hr(a){return rb(this.a,a)};_.Kb=function Ir(){return Il(),new dm(this.a)};_.Y=function Kr(){return 1};var Ny=Nkb(xyb,'SingletonImmutableSet',135);hI(285,342,{207:1,3:1,22:1,19:1},Ur,Vr);_.Bb=function Wr(a,b){return Lr(this,a,b)};_.Cb=function Xr(a){return Pr(this,a)};_.Db=function Yr(){return $s(Or(this,(qs(),os)))};_.Eb=function $r(){return new ks(this)};_.Fb=function _r(a,b){return Sr(this,a,b)};_.Gb=function as(a,b){return Tr(this,a,b)};_.Hb=function bs(a,b,c){var d,e,f;Mh(c,'newCount');Mh(b,'oldCount');Xb(ok(this.b,a));f=this.c.a;if(!f){if(b==0){c>0&&Lr(this,a,c);return true}else{return false}}e=xv(mw,Yyb,26,1,12,1);d=Ms(f,this.d,a,b,c,e);Us(this.c,f,d);return e[0]==b};_.Y=function cs(){return $s(Or(this,(qs(),ps)))};var Wy=Nkb(xyb,'TreeMultiset',285);hI(619,658,{83:1},fs);_.Yb=function gs(){var a;a=this.b.c;return a==0?Pr(this.a,this.b.b):a};_.Zb=function hs(){return this.b.b};var Py=Nkb(xyb,'TreeMultiset/1',619);hI(620,1,Ayb,ks);_.H=function ms(){return js(this)};_.G=function ls(){return is(this)};_.I=function ns(){ec(!!this.b);Tr(this.c,this.b.b.b,0);this.b=null};var Qy=Nkb(xyb,'TreeMultiset/2',620);hI(205,17,Zyb);var os,ps;var Ty=Okb(xyb,'TreeMultiset/Aggregate',205,IF,ss);hI(617,205,Zyb,ts);_._b=function us(a){return a.c};_.ac=function vs(a){return !a?0:a.j};var Ry=Okb(xyb,'TreeMultiset/Aggregate/1',617,Ty,null);hI(618,205,Zyb,ws);_._b=function xs(a){return 1};_.ac=function ys(a){return !a?0:a.a};var Sy=Okb(xyb,'TreeMultiset/Aggregate/2',618,Ty,null);hI(206,658,{83:1,206:1},Os);_.Yb=function Ps(){return this.c};_.Zb=function Qs(){return this.b};_.w=function Ss(){return Dq(),pq(new Lq(this.b,this.c))};_.a=0;_.c=0;_.d=0;_.j=0;var Uy=Nkb(xyb,'TreeMultiset/AvlNode',206);hI(616,1,{},Vs);var Vy=Nkb(xyb,'TreeMultiset/Reference',616);var $y=Nkb(lyb,'JavaScriptObject$',0);var qt;hI(628,1,{});var _y=Nkb(lyb,'Scheduler',628);var ut=0,vt=0,wt=-1;hI(360,628,{},Jt);var Ft;var az=Nkb(myb,'SchedulerImpl',360);hI(646,1,{});_.hc=function bu(){return null};_.ic=function cu(){return null};_.jc=function du(){return null};_.kc=function eu(){return null};_.lc=function fu(){return null};var nz=Nkb(_yb,'JSONValue',646);hI(214,646,{214:1},ju,ku);_.t=function lu(a){if(!aw(a,214)){return false}return this.a==Wv(a,214).a};_.gc=function mu(){return qu};_.v=function nu(){return txb(this.a)};_.hc=function ou(){return this};_.w=function pu(){var a,b,c;c=new Bmb('[');for(b=0,a=this.a.length;b<a;b++){b>0&&(c.a+=',',c);xmb(c,gu(this,b))}c.a+=']';return c.a};var fz=Nkb(_yb,'JSONArray',214);hI(292,646,{},uu);_.gc=function vu(){return yu};_.ic=function wu(){return this};_.w=function xu(){return Bkb(this.a)};_.a=false;var ru,su;var gz=Nkb(_yb,'JSONBoolean',292);hI(371,72,Vxb,zu);var hz=Nkb(_yb,'JSONException',371);hI(435,646,{},Cu);_.gc=function Du(){return Fu};_.w=function Eu(){return Wxb};var Au;var iz=Nkb(_yb,'JSONNull',435);hI(104,646,{104:1},Gu);_.t=function Hu(a){if(!aw(a,104)){return false}return this.a==Wv(a,104).a};_.gc=function Iu(){return Mu};_.v=function Ju(){return hw(Ixb(this.a))};_.jc=function Ku(){return this};_.w=function Lu(){return this.a+''};_.a=0;var jz=Nkb(_yb,'JSONNumber',104);hI(69,646,{69:1},Tu,Uu);_.t=function Vu(a){if(!aw(a,69)){return false}return this.a==Wv(a,69).a};_.gc=function Wu(){return $u};_.v=function Xu(){return txb(this.a)};_.kc=function Yu(){return this};_.w=function Zu(){var a,b,c,d,e,f;f=new Bmb('{');a=true;e=Nu(this,xv($F,Txb,2,0,5,1));for(c=0,d=e.length;c<d;++c){b=e[c];a?(a=false):(f.a+=', ',f);ymb(f,st(b));f.a+=':';xmb(f,Pu(this,b))}f.a+='}';return f.a};var lz=Nkb(_yb,'JSONObject',69);hI(361,641,Eyb,_u);_.kb=function av(a){return ew(a)&&Ou(this.a,$v(a))};_.mb=function bv(){return new wnb(new opb(this.b))};_.Y=function cv(){return this.b.length};var kz=Nkb(_yb,'JSONObject/1',361);var dv;hI(97,646,{97:1},lv);_.t=function mv(a){if(!aw(a,97)){return false}return emb(this.a,Wv(a,97).a)};_.gc=function nv(){return rv};_.v=function ov(){return Pxb(this.a)};_.lc=function pv(){return this};_.w=function qv(){return st(this.a)};var mz=Nkb(_yb,'JSONString',97);var Ov,Pv,Qv;hI(186,1,{},sI,tI);_.b=false;_.c=0;_.d=-1;_.e=0;_.f=false;_.j=0;var oz=Nkb('de.cau.cs.kieler.core.alg','BasicProgressMonitor',186);hI(10,1,{10:1,286:1,3:1,5:1},FI,GI,HI,II);_.t=function JI(a){return yI(this,a)};_.v=function KI(){return hw(Ixb(this.a))+Blb(hw(Ixb(this.b)))};_.w=function NI(){return '('+this.a+','+this.b+')'};_.a=0;_.b=0;var qz=Nkb(izb,'KVector',10);hI(58,648,{3:1,5:1,22:1,19:1,58:1,20:1},aJ);_.ib=function bJ(a){return QI(this,a)};_.Q=function cJ(){_I(this)};_.ub=function dJ(a){return WI(this,a)};_.Y=function eJ(){return this.b};_.b=0;var rH=Nkb(Cyb,'LinkedList',58);hI(44,58,{44:1,286:1,3:1,5:1,22:1,19:1,58:1,20:1},jJ,kJ);_.w=function mJ(){var a,b,c;a=new Bmb('(');b=WI(this,0);while(b.b!=b.d.c){c=Wv(_ub(b),10);ymb(a,c.a+','+c.b);b.b!=b.d.c&&(a.a+='; ',a)}return a.a+=')',a.a};var pz=Nkb(izb,'KVectorChain',44);var rz=Pkb(kzb,'IProperty');hI(131,1,{179:1,131:1,3:1},tJ);var sz=Nkb(kzb,'MapPropertyHolder',131);hI(14,1,lzb,AJ,BJ,CJ,DJ,EJ,FJ);_.F=function GJ(a){return xJ(this,Wv(a,79))};_.t=function HJ(a){return yJ(this,a)};_.mc=function IJ(){return this.b};_.nc=function JJ(){return this.c};_.oc=function KJ(){return this.d};_.v=function LJ(){return Pxb(this.b)};_.w=function MJ(){return this.b};var uJ,vJ;var vz=Nkb(kzb,'Property',14);hI(366,1,{23:1},NJ);_.F=function OJ(a){return -1};var tz=Nkb(kzb,'Property/1',366);hI(367,1,{23:1},PJ);_.F=function QJ(a){return 1};var uz=Nkb(kzb,'Property/2',367);hI(27,1,{27:1,22:1},RJ);_.t=function SJ(a){var b,c,d;if(aw(a,27)){c=Wv(a,27);b=this.a==null?c.a==null:rb(this.a,c.a);d=this.b==null?c.b==null:rb(this.b,c.b);return b&&d}else{return false}};_.v=function TJ(){var a,b,c,d,e,f;c=this.a==null?0:vb(this.a);a=c&byb;b=c&-65536;f=this.b==null?0:vb(this.b);d=f&byb;e=f&-65536;return a^e>>16&byb|b^d<<16};_.mb=function UJ(){return new WJ(this)};_.w=function VJ(){return this.a==null&&this.b==null?'pair(null,null)':this.a==null?'pair(null,'+xb(this.b)+')':this.b==null?'pair('+xb(this.a)+',null)':'pair('+xb(this.a)+','+xb(this.b)+')'};var xz=Nkb(mzb,'Pair',27);hI(431,1,Ayb,WJ);_.G=function XJ(){return !this.c&&(!this.b&&this.a.a!=null||this.a.b!=null)};_.H=function YJ(){if(!this.c&&!this.b&&this.a.a!=null){this.b=true;return this.a.a}else if(!this.c&&this.a.b!=null){this.c=true;return this.a.b}throw new nvb};_.I=function ZJ(){this.c&&this.a.b!=null?(this.a.b=null):this.b&&this.a.a!=null&&(this.a.a=null);throw new tlb};_.b=false;_.c=false;var wz=Nkb(mzb,'Pair/1',431);hI(228,72,Vxb,$J);var yz=Nkb(nzb,'UnsupportedConfigurationException',228);hI(99,72,Vxb,_J);var zz=Nkb(nzb,'UnsupportedGraphException',99);var aK;hI(103,17,{103:1,3:1,23:1,17:1},jK);var cK,dK,eK,fK,gK,hK;var Az=Okb(rzb,'Alignment',103,IF,kK);var lK;hI(59,17,{59:1,3:1,23:1,17:1},wK);var nK,oK,pK,qK,rK;var Bz=Okb(rzb,'Direction',59,IF,xK);var yK;hI(107,17,{107:1,3:1,23:1,17:1},FK);var AK,BK,CK,DK;var Cz=Okb(rzb,'EdgeLabelPlacement',107,IF,GK);var HK;hI(122,17,{122:1,3:1,23:1,17:1},OK);var JK,KK,LK,MK;var Dz=Okb(rzb,'EdgeRouting',122,IF,PK);var QK;hI(133,17,{133:1,3:1,23:1,17:1},ZK);var SK,TK,UK,VK,WK,XK;var Ez=Okb(rzb,'EdgeType',133,IF,$K);var _K;hI(166,17,{166:1,3:1,23:1,17:1},fL);var bL,cL,dL;var Fz=Okb(rzb,'HierarchyHandling',166,IF,gL);var hL;var jL,kL,lL,mL,nL,oL,pL,qL,rL,sL,tL,uL,vL,wL,xL,yL,zL,AL,BL,CL,DL,EL,FL,GL,HL,IL,JL,KL,LL,ML,NL,OL,PL,QL,RL,SL,TL,UL,VL,WL,XL,YL,ZL,$L,_L,aM,bM,cM,dM;hI(41,17,{41:1,3:1,23:1,17:1},pM);var fM,gM,hM,iM,jM,kM,lM,mM,nM;var Gz=Okb(rzb,'NodeLabelPlacement',41,IF,qM);var rM;hI(100,17,{100:1,3:1,23:1,17:1},AM);var uM,vM,wM,xM,yM;var Hz=Okb(rzb,'PortAlignment',100,IF,BM);var CM;hI(28,17,{28:1,3:1,23:1,17:1},NM);var EM,FM,GM,HM,IM,JM;var Iz=Okb(rzb,'PortConstraints',28,IF,OM);var PM;hI(149,17,{149:1,3:1,23:1,17:1},VM);var RM,SM,TM;var Jz=Okb(rzb,'PortLabelPlacement',149,IF,WM);var XM;hI(32,17,{32:1,3:1,23:1,17:1},uN);var ZM,$M,_M,aN,bN,cN,dN,eN,fN,gN,hN,iN,jN,kN,lN,mN,nN,oN,pN,qN,rN;var Kz=Okb(rzb,'PortSide',32,IF,wN);var xN;hI(150,17,{150:1,3:1,23:1,17:1},EN);var zN,AN,BN,CN;var Lz=Okb(rzb,'SizeConstraint',150,IF,FN);var GN;hI(139,17,{139:1,3:1,23:1,17:1},NN);var IN,JN,KN,LN;var Mz=Okb(rzb,'SizeOptions',139,IF,ON);var PN;hI(62,1,{62:1},UN,VN);_.t=function WN(a){var b;if(a==null||!aw(a,62)){return false}b=Wv(a,62);return ovb(this.d,b.d)&&ovb(this.e,b.e)&&ovb(this.c,b.c)&&ovb(this.b,b.b)};_.v=function XN(){return fpb(Bv(tv(UF,1),syb,1,4,[this.d,this.e,this.c,this.b]))};_.w=function YN(){return 'Rect[x='+this.d+',y='+this.e+',w='+this.c+',h='+this.b+']'};_.b=0;_.c=0;_.d=0;_.e=0;var Tz=Nkb(wzb,'Rectangle',62);hI(283,62,{283:1,62:1},ZN);_.a=0;var Nz=Nkb(xzb,'LabelGroup',283);hI(67,17,{67:1,3:1,23:1,17:1},vO);var $N,_N,aO,bO,cO,dO,eO,fO,gO,hO,iO,jO,kO,lO,mO,nO,oO,pO,qO,rO,sO,tO;var Oz=Okb(xzb,'LabelLocation',67,IF,xO);hI(225,17,{225:1,3:1,23:1,17:1},EO);var AO,BO,CO;var Pz=Okb(xzb,'TextAlignment',225,IF,FO);var HO;hI(589,1,{},fP);_.a=0;_.b=false;_.d=0;_.f=0;_.k=0;_.r=0;_.s=0;var Qz=Nkb(wzb,'LabelAndNodeSizeProcessor/NodeData',589);hI(171,17,{171:1,3:1,23:1,17:1},lP);var gP,hP,iP,jP;var Rz=Okb(wzb,'LabelSide',171,IF,mP);hI(590,1,{},rP);_.b=true;_.c=true;_.d=true;_.e=true;var Sz=Nkb(wzb,zzb,590);hI(121,1,Bzb);_.t=function wP(a){var b;if(aw(a,121)){b=Wv(a,121);return this.d==b.d&&this.a==b.a&&this.b==b.b&&this.c==b.c}else{return false}};_.v=function xP(){var a,b;a=hw(Ixb(this.b))<<16;a|=hw(Ixb(this.a))&byb;b=hw(Ixb(this.c))<<16;b|=hw(Ixb(this.d))&byb;return a^b};_.w=function zP(){return '[top='+this.d+',left='+this.b+',bottom='+this.a+',right='+this.c+']'};_.a=0;_.b=0;_.c=0;_.d=0;var Wz=Nkb(wzb,'Spacing',121);hI(232,121,Bzb,AP,BP,CP);var Uz=Nkb(wzb,'Spacing/Insets',232);hI(65,121,{286:1,121:1,65:1,3:1,5:1},DP,EP,FP);var Vz=Nkb(wzb,'Spacing/Margins',65);hI(364,1,{},jQ);_.c=false;_.d=null;_.g=null;var OP,PP,QP;var Xz=Nkb(Ozb,'JsonGraphImporter',364);var kQ,lQ,mQ,nQ,oQ,pQ,qQ,rQ,sQ;hI(417,14,lzb,xQ);var Yz=Nkb(Ozb,'LayoutOptionResolver/DummyProperty',417);hI(348,1,{},CQ);var yQ;var Zz=Nkb(Ozb,'RecursiveLGraphLayout',348);hI(73,99,{73:1,3:1,54:1,46:1},EQ,FQ,GQ);var $z=Nkb(Ozb,'UnsupportedJsonGraphException',73);hI(380,1,{},OQ);var HQ,IQ;var _z=Nkb(Szb,'GraphConfigurator',380);hI(49,1,{},WQ);var aA=Nkb(Szb,'IntermediateProcessingConfiguration',49);hI(365,1,{},dR);var bA=Nkb(Szb,'KlayLayered',365);hI(577,1,{},kR);_.i=0;var eR;var eA=Nkb(Wzb,'ComponentsToCGraphTransformer',577);var UR;hI(578,1,{},lR);_.tc=function mR(a,b){return Qlb(a.wc(),b.wc())};_.uc=function nR(a,b){return Qlb(a.xc(),b.xc())};var cA=Nkb(Wzb,'ComponentsToCGraphTransformer/1',578);hI(25,1,{25:1});_.k=0;_.o=null;_.p=true;_.r=Vzb;var kA=Nkb(Xzb,'CNode',25);hI(198,25,{198:1,25:1},pR,qR);_.vc=function rR(){this.b.d=this.j.d;this.b.e=this.j.e};_.wc=function sR(){return this.a!=null?Ixb(this.a):this.c.i};_.xc=function tR(){return this.a!=null?Ixb(this.a):this.c.i};_.w=function uR(){return ''};var dA=Nkb(Wzb,'ComponentsToCGraphTransformer/CRectNode',198);hI(549,1,{},HR);var vR,wR;var hA=Nkb(Wzb,'OneDimensionalComponentsCompaction',549);hI(550,1,Tyb,IR);_.B=function JR(a){return xR(),xkb(),Wv(Wv(a,27).a,25).f.f!=0?wkb:vkb};var fA=Nkb(Wzb,'OneDimensionalComponentsCompaction/lambda$0$Type',550);hI(551,1,Tyb,KR);_.B=function LR(a){return xR(),xkb(),uS(Wv(Wv(a,27).a,25).n,Wv(Wv(a,27).b,59))||Wv(Wv(a,27).a,25).f.f!=0&&uS(Wv(Wv(a,27).a,25).n,Wv(Wv(a,27).b,59))?wkb:vkb};var gA=Nkb(Wzb,'OneDimensionalComponentsCompaction/lambda$1$Type',551);hI(324,1,{},NR);var iA=Nkb(Xzb,'CGraph',324);hI(78,1,{78:1},QR);_.b=0;_.c=0;_.d=0;_.f=0;_.i=true;_.j=Vzb;var jA=Nkb(Xzb,'CGroup',78);hI(470,1,{},WR);_.tc=function XR(a,b){return Nlb(a.wc(),b.wc())};_.uc=function YR(a,b){return Nlb(a.xc(),b.xc())};var lA=Nkb(Xzb,'ISpacingsHandler/1',470);hI(323,1,{},rS);_.e=false;var ZR,$R,_R;var nA=Nkb(Xzb,'OneDimensionalCompactor',323);hI(554,1,Tyb,sS);_.B=function tS(a){return aS(),xkb(),Wv(Wv(a,27).a,25).f.f!=0?wkb:vkb};var mA=Nkb(Xzb,'OneDimensionalCompactor/lambda$0$Type',554);hI(335,1,{},xS);_.a=false;_.b=false;_.c=false;_.d=false;var oA=Nkb(Xzb,'Quadruplet',335);hI(587,1,{},yS);_.Cc=function zS(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;k=Uzb;for(d=new Tob(a.a.b);d.a<d.c.c.length;){b=Wv(Rob(d),25);k=Qlb(k,b.f.g.j.d+b.g.a)}q=new aJ;for(h=new Tob(a.a.a);h.a<h.c.c.length;){g=Wv(Rob(h),78);g.j=k;g.f==0&&(TI(q,g,q.c.b,q.c),true)}while(q.b!=0){g=Wv(q.b==0?null:(Bxb(q.b!=0),$I(q,q.a.a)),78);e=g.g.j.d;for(n=(p=(new Snb(g.a.a)).a.bb().mb(),new Ynb(p));n.a.G();){l=(f=Wv(n.a.H(),21),Wv(f.yb(),25));s=g.j+l.g.a;l.f.i||l.j.d<s?(l.r=s):(l.r=l.j.d)}e-=g.g.r;g.b+=e;a.d==(sK(),pK)||a.d==nK?(g.c+=e):(g.c-=e);for(m=(o=(new Snb(g.a.a)).a.bb().mb(),new Ynb(o));m.a.G();){l=(f=Wv(m.a.H(),21),Wv(f.yb(),25));for(j=l.i.mb();j.G();){i=Wv(j.H(),25);tK(a.d)?(r=a.g.tc(l,i)):(r=a.g.uc(l,i));i.f.j=Nlb(i.f.j,l.r+l.j.c+r-i.g.a);i.p||(i.f.j=Nlb(i.f.j,i.j.d-i.g.a));--i.f.f;i.f.f==0&&QI(q,i.f)}}}for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);b.j.d=b.r}};var pA=Nkb(Zzb,'LongestPathCompaction',587);hI(588,1,{},AS);_.Dc=function BS(a){var b,c,d,e,f,g,h;for(c=new Tob(a.a.b);c.a<c.c.c.length;){b=Wv(Rob(c),25);b.i.Q()}for(e=new Tob(a.a.b);e.a<e.c.c.length;){d=Wv(Rob(e),25);for(g=new Tob(a.a.b);g.a<g.c.c.length;){f=Wv(Rob(g),25);if(d==f){continue}if(!!d.f&&d.f==f.f){continue}tK(a.d)?(h=a.g.uc(d,f)):(h=a.g.tc(d,f));d!=f.o&&(f.j.d>d.j.d||d.j.d==f.j.d&&d.j.c<f.j.c)&&SR(f.j.e+f.j.b+h,d.j.e)&&TR(f.j.e,d.j.e+d.j.b+h)&&d.i.ib(f)}}};var qA=Nkb(Zzb,'QuadraticConstraintCalculation',588);hI(317,1,{},FS);_.Dc=function GS(a){this.b=a;ES(this,new RS,new TS)};var xA=Nkb(Zzb,'ScanlineConstraintCalculator',317);var JA=Pkb($zb,'Scanline/EventHandler');hI(464,1,{160:1},KS);_.Ec=function LS(a){IS(this,Wv(a,235))};var sA=Nkb(Zzb,'ScanlineConstraintCalculator/ConstraintsScanlineHandler',464);hI(465,1,fyb,MS);_.$b=function NS(a,b){return glb((Wv(a,25).j.d+Wv(a,25).j.c)/2,(Wv(b,25).j.d+Wv(b,25).j.c)/2)};var rA=Nkb(Zzb,'ScanlineConstraintCalculator/ConstraintsScanlineHandler/lambda$0$Type',465);hI(235,1,{235:1},OS);_.a=false;var tA=Nkb(Zzb,'ScanlineConstraintCalculator/Timestamp',235);hI(466,1,fyb,PS);_.$b=function QS(a,b){return HS(a,b)};var uA=Nkb(Zzb,'ScanlineConstraintCalculator/lambda$0$Type',466);hI(467,1,_zb,RS);_.D=function SS(a){return true};var vA=Nkb(Zzb,'ScanlineConstraintCalculator/lambda$1$Type',467);hI(468,1,Tyb,TS);_.B=function US(a){return 0};var wA=Nkb(Zzb,'ScanlineConstraintCalculator/lambda$2$Type',468);hI(48,1,{48:1},VS,WS);_.t=function XS(a){var b;if(a==null){return false}if(zA!=tb(a)){return false}b=Wv(a,48);return ovb(this.c,b.c)&&ovb(this.d,b.d)};_.v=function YS(){return fpb(Bv(tv(UF,1),syb,1,4,[this.c,this.d]))};_.w=function ZS(){return '('+this.c+', '+this.d+(this.a?'cx':'')+this.b+')'};_.a=true;_.c=0;_.d=0;var zA=Nkb($zb,'Point',48);hI(201,17,{201:1,3:1,23:1,17:1},fT);var $S,_S,aT,bT;var yA=Okb($zb,'Point/Quadrant',201,IF,iT);hI(569,1,{},qT);_.b=null;_.c=null;_.d=null;_.e=null;_.f=null;var jT,kT,lT,mT,nT;var IA=Nkb($zb,'RectilinearConvexHull',569);hI(243,1,{160:1},xT);_.Ec=function yT(a){wT(this,Wv(a,48))};_.b=0;var uT;var BA=Nkb($zb,'RectilinearConvexHull/MaximalElementsEventHandler',243);hI(571,1,fyb,AT);_.$b=function BT(a,b){return zT(a,b)};var AA=Nkb($zb,'RectilinearConvexHull/MaximalElementsEventHandler/lambda$0$Type',571);hI(570,1,{160:1},DT);_.Ec=function ET(a){CT(this,Wv(a,48))};_.a=0;_.b=null;_.c=null;_.d=null;_.e=null;var CA=Nkb($zb,'RectilinearConvexHull/RectangleEventHandler',570);hI(572,1,fyb,FT);_.$b=function GT(a,b){return oT(),Wv(a,48).c==Wv(b,48).c?glb(Wv(b,48).d,Wv(a,48).d):glb(Wv(a,48).c,Wv(b,48).c)};var DA=Nkb($zb,'RectilinearConvexHull/lambda$0$Type',572);hI(573,1,fyb,HT);_.$b=function IT(a,b){return oT(),Wv(a,48).c==Wv(b,48).c?glb(Wv(a,48).d,Wv(b,48).d):glb(Wv(a,48).c,Wv(b,48).c)};var EA=Nkb($zb,'RectilinearConvexHull/lambda$1$Type',573);hI(574,1,fyb,JT);_.$b=function KT(a,b){return oT(),Wv(a,48).c==Wv(b,48).c?glb(Wv(b,48).d,Wv(a,48).d):glb(Wv(b,48).c,Wv(a,48).c)};var FA=Nkb($zb,'RectilinearConvexHull/lambda$2$Type',574);hI(575,1,fyb,LT);_.$b=function MT(a,b){return oT(),Wv(a,48).c==Wv(b,48).c?glb(Wv(a,48).d,Wv(b,48).d):glb(Wv(b,48).c,Wv(a,48).c)};var GA=Nkb($zb,'RectilinearConvexHull/lambda$3$Type',575);hI(576,1,fyb,NT);_.$b=function OT(a,b){return sT(a,b)};var HA=Nkb($zb,'RectilinearConvexHull/lambda$4$Type',576);hI(469,1,{},QT);var KA=Nkb($zb,'Scanline',469);hI(662,1,{});var LA=Nkb(aAb,'AbstractGraphPlacer',662);hI(222,1,{222:1},_T);var WT;var NA=Nkb(aAb,'ComponentGroup',222);hI(434,662,{},fU);_.Fc=function gU(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;this.a.c=xv(UF,syb,1,0,4,1);b.b.c=xv(UF,syb,1,0,4,1);if(a.V()){b.e.a=0;b.e.b=0;return}f=Wv(a.sb(0),55);qJ(b,f);for(e=a.mb();e.G();){d=Wv(e.H(),55);aU(this,d)}n=new FI;o=2*Wv(rJ(f,(Rib(),Jib)),15).a;for(i=new Tob(this.a);i.a<i.c.c.length;){g=Wv(Rob(i),222);j=bU(g,o);VT(Jd(g.a),n.a,n.b);n.a+=j.a;n.b+=j.b}b.e.a=n.a-o;b.e.b=n.b-o;if(Ckb(Ixb(Xv(rJ(f,(Mjb(),ijb)))))&&gw(rJ(f,(eM(),uL)))===gw((NK(),JK))){for(m=a.mb();m.G();){k=Wv(m.H(),55);UT(k,k.d.a,k.d.b)}c=new sU;iU(c,a,o);for(l=a.mb();l.G();){k=Wv(l.H(),55);vI(BI(k.d),c.e)}vI(BI(b.e),c.a)}for(h=new Tob(this.a);h.a<h.c.c.length;){g=Wv(Rob(h),222);TT(b,Jd(g.a))}};var MA=Nkb(aAb,'ComponentGroupGraphPlacer',434);hI(322,1,{},sU);var VA=Nkb(aAb,'ComponentsCompactor',322);hI(13,647,bAb,GU,HU,IU);_.rb=function JU(a,b){uU(this,a,b)};_.ib=function KU(a){return vU(this,a)};_.jb=function LU(a){return xU(this,a)};_.Q=function MU(){this.c=xv(UF,syb,1,0,4,1)};_.kb=function NU(a){return zU(this,a,0)!=-1};_.sb=function OU(a){return yU(this,a)};_.V=function PU(){return this.c.length==0};_.mb=function QU(){return new Tob(this)};_.vb=function RU(a){return AU(this,a)};_.nb=function SU(a){return BU(this,a)};_.Xb=function TU(a,b){CU(this,a,b)};_.wb=function UU(a,b){return DU(this,a,b)};_.Y=function VU(){return this.c.length};_.ob=function WU(){return EU(this)};_.pb=function XU(a){return FU(this,a)};var BG=Nkb(Cyb,'ArrayList',13);hI(532,13,bAb,$U);_.ib=function _U(a){return ZU(this,Wv(a,48))};var OA=Nkb(aAb,'ComponentsCompactor/Hullpoints',532);hI(529,1,{347:1},bV);_.a=false;var PA=Nkb(aAb,'ComponentsCompactor/InternalComponent',529);hI(528,1,Oyb,cV);_.mb=function dV(){return new Tob(this.a)};var QA=Nkb(aAb,'ComponentsCompactor/InternalConnectedComponents',528);hI(531,1,{251:1},eV);_.zc=function gV(){return null};_.Ac=function hV(){return this.a};_.yc=function fV(){return oU(this.d)};_.Bc=function iV(){return this.b};var RA=Nkb(aAb,'ComponentsCompactor/InternalExternalExtension',531);hI(530,1,{251:1},jV);_.Ac=function mV(){return this.a};_.yc=function kV(){return oU(this.d)};_.zc=function lV(){return this.c};_.Bc=function nV(){return this.b};var SA=Nkb(aAb,'ComponentsCompactor/InternalUnionExternalExtension',530);hI(534,1,{},oV);var TA=Nkb(aAb,'ComponentsCompactor/OuterSegments',534);hI(533,1,{},pV);var UA=Nkb(aAb,'ComponentsCompactor/Segments',533);hI(381,1,{},tV);var WA=Nkb(aAb,'ComponentsProcessor',381);hI(432,662,{},uV);_.Fc=function vV(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A;if(a.Y()==1){t=Wv(a.sb(0),55);if(t!=b){b.b.c=xv(UF,syb,1,0,4,1);ST(b,t,0,0);qJ(b,t);YW(b.a,t.a);b.e.a=t.e.a;b.e.b=t.e.b}return}else if(a.V()){b.b.c=xv(UF,syb,1,0,4,1);b.e.a=0;b.e.b=0;return}for(h=a.mb();h.G();){f=Wv(h.H(),55);q=0;for(o=new Tob(f.b);o.a<o.c.c.length;){n=Wv(Rob(o),9);q+=Wv(rJ(n,(Rib(),Eib)),24).a}f.k=q}Gpb(a,new xV);e=Wv(a.sb(0),55);b.b.c=xv(UF,syb,1,0,4,1);qJ(b,e);m=0;v=0;for(i=a.mb();i.G();){f=Wv(i.H(),55);s=f.e;m=Nlb(m,s.a);v+=s.a*s.b}m=Nlb(m,Math.sqrt(v)*Wv(rJ(b,(Rib(),Rhb)),15).a);u=cAb*Wv(rJ(b,Jib),15).a;w=0;A=0;l=0;c=u;for(g=a.mb();g.G();){f=Wv(g.H(),55);s=f.e;if(w+s.a>m){w=0;A+=l+u;l=0}p=f.d;UT(f,w+p.a,A+p.b);p.a=0;p.b=0;c=Nlb(c,w+s.a);l=Nlb(l,s.b);w+=s.a+u}b.e.a=c;b.e.b=A+l;r=Wv(rJ(b,Jib),15).a;if(Ckb(Ixb(Xv(rJ(e,(Mjb(),ijb)))))){d=new sU;iU(d,a,r);for(k=a.mb();k.G();){j=Wv(k.H(),55);vI(BI(j.d),d.e)}vI(BI(b.e),d.a)}TT(b,a)};var YA=Nkb(aAb,'SimpleRowGraphPlacer',432);hI(433,1,fyb,xV);_.$b=function yV(a,b){return wV(Wv(a,55),Wv(b,55))};var XA=Nkb(aAb,'SimpleRowGraphPlacer/1',433);hI(369,1,eAb,CV);_.sc=function DV(a,b){BV(a,b)};var zV;var $A=Nkb(fAb,'CompoundGraphPostprocessor',369);hI(370,1,_zb,EV);_.D=function FV(a){var b;return b=Wv(rJ(Wv(a,114).b,(eM(),CL)),44),!!b&&b.b!=0};var ZA=Nkb(fAb,'CompoundGraphPostprocessor/1',370);hI(368,1,eAb,SV);_.sc=function TV(a,b){NV(this,a,b)};var aB=Nkb(fAb,'CompoundGraphPreprocessor',368);hI(187,1,{187:1},UV);_.c=false;var _A=Nkb(fAb,'CompoundGraphPreprocessor/ExternalPort',187);hI(114,1,{114:1},XV);_.w=function YV(){return zc(this.c)+':'+gW(this.b)};var cB=Nkb(fAb,'CrossHierarchyEdge',114);hI(310,1,fyb,$V);_.$b=function _V(a,b){return ZV(this,Wv(a,114),Wv(b,114))};var bB=Nkb(fAb,'CrossHierarchyEdgeComparator',310);hI(147,131,{179:1,131:1,147:1,3:1});_.k=0;var lB=Nkb(hAb,'LGraphElement',147);hI(12,147,{179:1,131:1,12:1,147:1,3:1},hW);_.w=function iW(){return gW(this)};var dB=Nkb(hAb,'LEdge',12);hI(55,147,{179:1,131:1,55:1,147:1,3:1,22:1},kW);_.mb=function lW(){return new Tob(this.c)};_.w=function mW(){if(this.c.c.length==0){return 'G-unlayered'+Ze(this.b)}else if(this.b.c.length==0){return 'G-layered'+Ze(this.c)}return 'G[layerless'+Ze(this.b)+', layers'+Ze(this.c)+']'};var mB=Nkb(hAb,'LGraph',55);hI(273,1,{});_.pc=function rW(){return this.e.j};var eB=Nkb(hAb,'LGraphAdapters/AbstractLShapeAdapter',273);hI(240,1,{627:1},tW);_.b=null;var fB=Nkb(hAb,'LGraphAdapters/LEdgeAdapter',240);hI(325,1,{},wW);_.pc=function xW(){return this.a.e};_.b=null;_.c=false;var gB=Nkb(hAb,'LGraphAdapters/LGraphAdapter',325);hI(224,273,{129:1,224:1},yW);var hB=Nkb(hAb,'LGraphAdapters/LLabelAdapter',224);hI(555,273,{626:1},BW);_.a=null;_.b=null;_.c=false;var iB=Nkb(hAb,'LGraphAdapters/LNodeAdapter',555);hI(556,273,{161:1},FW);_.a=null;_.b=null;_.c=null;_.d=false;var jB=Nkb(hAb,'LGraphAdapters/LPortAdapter',556);hI(557,1,fyb,HW);_.$b=function IW(a,b){return GW(Wv(a,7),Wv(b,7))};var kB=Nkb(hAb,'LGraphAdapters/PortComparator',557);hI(168,1,{168:1},ZW,$W);_.t=function _W(a){var b;if(aw(a,168)){b=Wv(a,168);return this.d==b.d&&this.a==b.a&&this.b==b.b&&this.c==b.c}else{return false}};_.v=function aX(){var a,b;a=hw(Ixb(this.b))<<16;a|=hw(Ixb(this.a))&byb;b=hw(Ixb(this.c))<<16;b|=hw(Ixb(this.d))&byb;return a^b};_.w=function bX(){return 'Insets[top='+this.d+',left='+this.b+',bottom='+this.a+',right='+this.c+']'};_.a=0;_.b=0;_.c=0;_.d=0;var nB=Nkb(hAb,'LInsets',168);hI(165,147,{179:1,131:1,147:1,165:1,3:1});var CB=Nkb(hAb,'LShape',165);hI(33,165,{179:1,131:1,147:1,33:1,165:1,3:1},dX);_.w=function eX(){return this.a==null?'l_'+this.k:'l_'+this.a};var oB=Nkb(hAb,'LLabel',33);hI(9,165,{179:1,131:1,147:1,9:1,165:1,3:1},uX);_.w=function vX(){return tX(this)};var qB=Nkb(hAb,'LNode',9);hI(132,17,{132:1,3:1,23:1,17:1},DX);var wX,xX,yX,zX,AX,BX;var pB=Okb(hAb,'LNode/NodeType',132,IF,EX);hI(7,165,{179:1,131:1,147:1,7:1,165:1,3:1},RX);_.w=function SX(){var a;return a=OX(this),a==null?'p_'+this.k:'p_'+a};var FX,GX,HX,IX,JX,KX;var BB=Nkb(hAb,'LPort',7);hI(399,1,_zb,UX);_.D=function VX(a){return TX(a)};var rB=Nkb(hAb,'LPort/1',399);hI(400,1,_zb,XX);_.D=function YX(a){return WX(a)};var sB=Nkb(hAb,'LPort/2',400);hI(401,1,_zb,ZX);_.D=function $X(a){return Wv(a,7).g==(sN(),$M)};var tB=Nkb(hAb,'LPort/3',401);hI(402,1,_zb,_X);_.D=function aY(a){return Wv(a,7).g==(sN(),ZM)};var uB=Nkb(hAb,'LPort/4',402);hI(403,1,_zb,bY);_.D=function cY(a){return Wv(a,7).g==(sN(),pN)};var vB=Nkb(hAb,'LPort/5',403);hI(404,1,_zb,dY);_.D=function eY(a){return Wv(a,7).g==(sN(),rN)};var wB=Nkb(hAb,'LPort/6',404);hI(190,1,Oyb,fY);_.mb=function gY(){var a;a=new Tob(this.a.b);return new hY(a)};var yB=Nkb(hAb,'LPort/7',190);hI(405,1,Ayb,hY);_.H=function jY(){return Wv(Rob(this.a),12).c};_.G=function iY(){return Qob(this.a)};_.I=function kY(){Sob(this.a)};var xB=Nkb(hAb,'LPort/7/1',405);hI(169,1,Oyb,lY);_.mb=function mY(){var a;return a=new Tob(this.a.e),new nY(a)};var AB=Nkb(hAb,'LPort/8',169);hI(304,1,Ayb,nY);_.H=function pY(){return Wv(Rob(this.a),12).d};_.G=function oY(){return Qob(this.a)};_.I=function qY(){Sob(this.a)};var zB=Nkb(hAb,'LPort/8/1',304);hI(16,147,{179:1,131:1,147:1,16:1,3:1,22:1},sY);_.mb=function tY(){return new Tob(this.a)};_.w=function uY(){return 'L_'+zU(this.b.c,this,0)+Ze(this.a)};var DB=Nkb(hAb,'Layer',16);hI(437,1,eAb,wY);_.sc=function xY(a,b){var c,d,e,f,g,h,i;nI(b,'Big nodes intermediate-processing',1);this.a=a;for(f=new Tob(this.a.c);f.a<f.c.c.length;){e=Wv(Rob(f),16);i=Eo(e.a);c=pl(i,new zY);for(h=Pl(c.b.mb(),c.a);od(h);){g=Wv(pd(h),9);if(gw(rJ(g,(Mjb(),vjb)))===gw((Xib(),Uib))||gw(rJ(g,vjb))===gw(Vib)){d=vY(this,g,false);sJ(d,vjb,Wv(rJ(g,vjb),85));sJ(g,vjb,Wib)}else{vY(this,g,true)}}}pI(b)};var FB=Nkb(jAb,'BigNodesIntermediateProcessor',437);hI(438,1,_zb,zY);_.D=function AY(a){return yY(Wv(a,9))};var EB=Nkb(jAb,'BigNodesIntermediateProcessor/1',438);hI(582,1,Tyb,CY);_.B=function DY(a){var b;return BY((b=this,iw(a),b))};var GB=Nkb(jAb,'BigNodesLabelHandler/CompoundFunction',582);hI(332,1,{},HY);_.a=0;_.e=null;_.f=0;var KB=Nkb(jAb,'BigNodesLabelHandler/Handler',332);hI(583,1,Tyb,JY);_.B=function KY(a){var b;return IY((b=this,iw(a),b))};var HB=Nkb(jAb,'BigNodesLabelHandler/Handler/1',583);hI(584,1,Tyb,MY);_.B=function NY(a){var b;return LY((b=this,iw(a),b))};var IB=Nkb(jAb,'BigNodesLabelHandler/Handler/2',584);hI(585,1,Tyb,PY);_.B=function QY(a){var b;return OY((b=this,iw(a),b))};var JB=Nkb(jAb,'BigNodesLabelHandler/Handler/3',585);hI(439,1,eAb,SY);_.sc=function TY(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;nI(b,'Big nodes post-processing',1);this.a=a;for(h=new Tob(this.a.c);h.a<h.c.c.length;){g=Wv(Rob(h),16);c=pl(g.a,new VY);for(j=Pl(c.b.mb(),c.a);od(j);){i=Wv(pd(j),9);l=Wv(rJ(i,(Rib(),Whb)),15);f=RY(this,i);p=new GU;for(o=nX(f,(sN(),ZM)).mb();o.G();){m=Wv(o.H(),7);p.c[p.c.length]=m;k=m.i.a-f.j.a;m.i.a=l.a+k}i.j.a=l.a;for(n=new Tob(p);n.a<n.c.c.length;){m=Wv(Rob(n),7);PX(m,i)}this.a.e.a<i.i.a+i.j.a&&(this.a.e.a=i.i.a+i.j.a);e=Wv(rJ(i,Thb),20);xU(i.c,e);d=Wv(rJ(i,Uhb),64);!!d&&d.B(null)}}pI(b)};var MB=Nkb(jAb,'BigNodesPostProcessor',439);hI(440,1,_zb,VY);_.D=function WY(a){return UY(Wv(a,9))};var LB=Nkb(jAb,'BigNodesPostProcessor/1',440);hI(441,1,eAb,YY);_.sc=function ZY(a,b){var c,d,e,f,g,h,i,j,k,l,m,n;nI(b,kAb,1);this.c=a;l=this.c.b;e=0;for(i=new Tob(l);i.a<i.c.c.length;){g=Wv(Rob(i),9);g.k=e++}this.d=Wv(rJ(this.c,(Rib(),Jib)),15).a;this.a=Wv(rJ(this.c,(eM(),sL)),59);this.b=l.c.length;f=lAb;for(j=new Tob(l);j.a<j.c.c.length;){g=Wv(Rob(j),9);g.g==(CX(),AX)&&g.j.a<f&&(f=g.j.a)}f=50>f?50:f;c=new GU;n=f+this.d;for(k=new Tob(l);k.a<k.c.c.length;){g=Wv(Rob(k),9);if(g.g==(CX(),AX)&&g.j.a>n){m=1;d=g.j.a;while(d>f){++m;d=(g.j.a-(m-1)*this.d)/m}vU(c,new _Y(this,g,m,d))}}for(h=new Tob(c);h.a<h.c.c.length;){g=Wv(Rob(h),267);XY(g.d)&&$Y(g)}pI(b)};_.b=0;_.d=0;var OB=Nkb(jAb,'BigNodesPreProcessor',441);hI(267,1,{267:1},_Y);_.a=0;_.c=0;var NB=Nkb(jAb,'BigNodesPreProcessor/BigNode',267);hI(442,1,eAb,cZ);_.sc=function dZ(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;nI(b,kAb,1);aZ=Ckb(Ixb(Xv(rJ(a,(eM(),rL)))));this.c=a;n=new GU;for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);xU(n,f.a)}e=0;for(k=new Tob(n);k.a<k.c.c.length;){i=Wv(Rob(k),9);i.k=e++}this.d=Wv(rJ(this.c,(Rib(),Jib)),15).a;this.a=Wv(rJ(this.c,sL),59);this.b=n.c.length;h=lAb;for(l=new Tob(n);l.a<l.c.c.length;){i=Wv(Rob(l),9);i.g==(CX(),AX)&&i.j.a<h&&(h=i.j.a)}h=50>h?50:h;c=new GU;p=h+this.d;for(m=new Tob(n);m.a<m.c.c.length;){i=Wv(Rob(m),9);if(i.g==(CX(),AX)&&i.j.a>p){o=1;d=i.j.a;while(d>h){++o;d=(i.j.a-(o-1)*this.d)/o}vU(c,new nZ(this,i,o))}}for(j=new Tob(c);j.a<j.c.c.length;){i=Wv(Rob(j),268);bZ(i)&&gZ(i)}pI(b)};_.b=0;_.d=0;var aZ=false;var QB=Nkb(jAb,'BigNodesSplitter',442);hI(268,1,{268:1},nZ);_.a=0;_.e=4;var PB=Nkb(jAb,'BigNodesSplitter/BigNode',268);hI(443,1,eAb,qZ);_.sc=function rZ(a,b){var c,d,e,f,g,h,i,j;nI(b,'Comment post-processing',1);i=Wv(rJ(a,(Rib(),Jib)),15).a;for(f=new Tob(a.c);f.a<f.c.c.length;){e=Wv(Rob(f),16);d=new GU;for(h=new Tob(e.a);h.a<h.c.c.length;){g=Wv(Rob(h),9);j=Wv(rJ(g,Qib),20);c=Wv(rJ(g,Yhb),20);if(!!j||!!c){pZ(g,j,c,i);!!j&&xU(d,j);!!c&&xU(d,c)}}xU(e.a,d)}pI(b)};var RB=Nkb(jAb,'CommentPostprocessor',443);hI(444,1,eAb,tZ);_.sc=function uZ(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q;nI(b,'Comment pre-processing',1);h=new Tob(a.b);while(h.a<h.c.c.length){g=Wv(Rob(h),9);if(Ckb(Ixb(Xv(rJ(g,(eM(),qL)))))){d=0;c=null;i=null;for(n=new Tob(g.f);n.a<n.c.c.length;){l=Wv(Rob(n),7);d+=l.b.c.length+l.e.c.length;if(l.b.c.length==1){c=Wv(yU(l.b,0),12);i=c.c}if(l.e.c.length==1){c=Wv(yU(l.e,0),12);i=c.d}}if(d==1&&i.b.c.length+i.e.c.length==1&&!Ckb(Ixb(Xv(rJ(i.f,qL))))){sZ(g,c,i,i.f);Sob(h)}else{q=new GU;for(m=new Tob(g.f);m.a<m.c.c.length;){l=Wv(Rob(m),7);for(k=new Tob(l.e);k.a<k.c.c.length;){j=Wv(Rob(k),12);j.d.e.c.length==0||(q.c[q.c.length]=j,true)}for(f=new Tob(l.b);f.a<f.c.c.length;){e=Wv(Rob(f),12);e.c.b.c.length==0||(q.c[q.c.length]=e,true)}}for(p=new Tob(q);p.a<p.c.c.length;){o=Wv(Rob(p),12);cW(o,true)}}}}pI(b)};var SB=Nkb(jAb,'CommentPreprocessor',444);hI(445,1,eAb,wZ);_.sc=function xZ(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Edge and layer constraint edge reversal',1);for(j=new Tob(a.b);j.a<j.c.c.length;){i=Wv(Rob(j),9);g=Wv(rJ(i,(Mjb(),vjb)),85);f=null;switch(g.e){case 1:case 2:f=(Hgb(),Ggb);break;case 3:case 4:f=(Hgb(),Egb);}if(f){sJ(i,(Rib(),dib),(Hgb(),Ggb));f==Egb?vZ(i,g,(djb(),bjb)):f==Ggb&&vZ(i,g,(djb(),ajb))}else{if(MM(Wv(rJ(i,(eM(),TL)),28))&&i.f.c.length!=0){c=true;for(l=new Tob(i.f);l.a<l.c.c.length;){k=Wv(Rob(l),7);if(!(k.g==(sN(),ZM)&&k.b.c.length-k.e.c.length>0||k.g==rN&&k.b.c.length-k.e.c.length<0)){c=false;break}if(k.g==rN){for(e=new Tob(k.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);h=Wv(rJ(d.d.f,vjb),85);if(h==(Xib(),Uib)||h==Vib){c=false;break}}}if(k.g==ZM){for(e=new Tob(k.b);e.a<e.c.c.length;){d=Wv(Rob(e),12);h=Wv(rJ(d.c.f,vjb),85);if(h==(Xib(),Sib)||h==Tib){c=false;break}}}}c&&vZ(i,g,(djb(),cjb))}}}pI(b)};var TB=Nkb(jAb,'EdgeAndLayerConstraintEdgeReverser',445);hI(446,1,eAb,AZ);_.sc=function BZ(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'End label placement',1);g=Wv(rJ(a,(eM(),DL)),15).a;this.a=(mp(),new ntb);this.c=new ntb;this.b=new ntb;for(i=new Tob(a.c);i.a<i.c.c.length;){h=Wv(Rob(i),16);for(k=new Tob(h.a);k.a<k.c.c.length;){j=Wv(Rob(k),9);for(d=Uh(mX(j));Cm(d);){c=Wv(Dm(d),12);for(f=new Tob(c.b);f.a<f.c.c.length;){e=Wv(Rob(f),33);(gw(rJ(e,tL))===gw((EK(),CK))||gw(rJ(e,tL))===gw(BK))&&(l=null,gw(rJ(e,tL))===gw(CK)?(l=c.c):gw(rJ(e,tL))===gw(BK)&&(l=c.d),Qmb(this.a,l.f)||Umb(this.a,l.f,0),Qmb(this.c,l.f)||Umb(this.c,l.f,0),Qmb(this.b,l)||Umb(this.b,l,0),gw(rJ(e,(Rib(),pib)))===gw((kP(),gP))?zZ(e,l,g):yZ(e,l,g),undefined)}}}}pI(b)};var UB=Nkb(jAb,'EndLabelProcessor',446);hI(269,1,eAb,SZ);_.sc=function TZ(a,b){var c,d,e,f,g;nI(b,'Graph transformation ('+this.a+')',1);e=Ao(a.b);for(d=new Tob(a.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);xU(e,c.a)}switch(this.a.e){case 0:JZ(e,a);break;case 1:NZ(e);g=Wv(rJ(a,(Mjb(),ojb)),115);!!g&&sJ(a,ojb,Qgb(g));MZ(a.d);MZ(a.e);break;case 2:JZ(e,a);LZ(e,a);NZ(e);f=Wv(rJ(a,(Mjb(),ojb)),115);!!f&&sJ(a,ojb,Qgb(f));MZ(a.d);MZ(a.e);}pI(b)};var WB=Nkb(jAb,'GraphTransformer',269);hI(221,17,{221:1,3:1,23:1,17:1},YZ);var UZ,VZ,WZ;var VB=Okb(jAb,'GraphTransformer/Mode',221,IF,ZZ);hI(448,1,eAb,d$);_.sc=function e$(a,b){nI(b,'Hierarchical port constraint processing',1);a$(a);c$(a);pI(b)};var YB=Nkb(jAb,'HierarchicalPortConstraintProcessor',448);hI(449,1,fyb,g$);_.$b=function h$(a,b){return f$(Wv(a,9),Wv(b,9))};var XB=Nkb(jAb,'HierarchicalPortConstraintProcessor/NodeComparator',449);hI(450,1,eAb,j$);_.sc=function k$(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Hierarchical port dummy size processing',1);i=new GU;l=new GU;h=Wv(rJ(a,(Rib(),Jib)),15).a;k=h*Wv(rJ(a,(Mjb(),qjb)),15).a;c=k*2;for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);i.c=xv(UF,syb,1,0,4,1);l.c=xv(UF,syb,1,0,4,1);for(g=new Tob(d.a);g.a<g.c.c.length;){f=Wv(Rob(g),9);if(f.g==(CX(),xX)){j=Wv(rJ(f,hib),32);j==(sN(),$M)?(i.c[i.c.length]=f,true):j==pN&&(l.c[l.c.length]=f,true)}}i$(i,true,c);i$(l,false,c)}pI(b)};var ZB=Nkb(jAb,'HierarchicalPortDummySizeProcessor',450);hI(451,1,eAb,w$);_.sc=function x$(a,b){var c,d,e,f;nI(b,'Orthogonally routing hierarchical port edges',1);this.a=0;c=s$(a);v$(a,c);u$(this,a,c);q$(a);d=Wv(rJ(a,(eM(),TL)),28);e=a.c;p$((Cxb(0,e.c.length),Wv(e.c[0],16)),d,a);p$(Wv(yU(e,e.c.length-1),16),d,a);f=a.c;n$((Cxb(0,f.c.length),Wv(f.c[0],16)));n$(Wv(yU(f,f.c.length-1),16));pI(b)};_.a=0;var aC=Nkb(jAb,'HierarchicalPortOrthogonalEdgeRouter',451);hI(452,1,fyb,z$);_.$b=function A$(a,b){return y$(Wv(a,9),Wv(b,9))};var $B=Nkb(jAb,'HierarchicalPortOrthogonalEdgeRouter/1',452);hI(453,1,fyb,C$);_.$b=function D$(a,b){return B$(Wv(a,9),Wv(b,9))};var _B=Nkb(jAb,'HierarchicalPortOrthogonalEdgeRouter/2',453);hI(454,1,eAb,F$);_.sc=function G$(a,b){var c;nI(b,'Hierarchical port position processing',1);c=a.c;c.c.length>0&&E$((Cxb(0,c.c.length),Wv(c.c[0],16)),a);c.c.length>1&&E$(Wv(yU(c,c.c.length-1),16),a);pI(b)};var bC=Nkb(jAb,'HierarchicalPortPositionProcessor',454);hI(471,1,eAb,I$);_.sc=function J$(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;nI(b,'Hyperedge merging',1);n=new Fnb(a.c,0);while(n.b<n.d.Y()){m=(Bxb(n.b<n.d.Y()),Wv(n.d.sb(n.c=n.b++),16));p=m.a;if(p.c.length==0){continue}h=null;l=null;for(o=0;o<p.c.length;o++){c=(Cxb(o,p.c.length),Wv(p.c[o],9));g=c.g;if(g==(CX(),zX)&&l==zX){e=Wv(rJ(c,(Rib(),qib)),7);j=Wv(rJ(h,qib),7);f=Wv(rJ(c,rib),7);k=Wv(rJ(h,rib),7);d=!!e||!!f;i=!!j||!!k;if(d&&i&&(e==j||f==k)){H$(c,h,e==j,f==k);Cxb(o,p.c.length);hxb(p.c,o,1);--o;c=h;g=l}}h=c;l=g}}pI(b)};var cC=Nkb(jAb,'HyperedgeDummyMerger',471);hI(472,1,eAb,L$);_.sc=function M$(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Hypernodes processing',1);for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);for(h=new Tob(d.a);h.a<h.c.c.length;){g=Wv(Rob(h),9);if(Ckb(Ixb(Xv(rJ(g,(eM(),AL)))))&&g.f.c.length<=2){l=0;k=0;c=0;f=0;for(j=new Tob(g.f);j.a<j.c.c.length;){i=Wv(Rob(j),7);switch(i.g.e){case 1:++l;break;case 2:++k;break;case 3:++c;break;case 4:++f;}}l==0&&c==0&&K$(a,g,f<=k)}}}pI(b)};var dC=Nkb(jAb,'HypernodesProcessor',472);hI(473,1,eAb,N$);_.sc=function O$(a,b){var c,d,e,f,g,h,i,j,k;nI(b,'Layer constraint edge reversal',1);for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);k=-1;c=new GU;j=Wv(FU(f.a,xv(qB,Nzb,9,f.a.c.length,0,1)),51);for(e=0;e<j.length;e++){d=Wv(rJ(j[e],(Rib(),mib)),140);if(k==-1){d!=(Hhb(),Ghb)&&(k=e)}else{if(d==(Hhb(),Ghb)){rX(j[e],null);qX(j[e],k++,f)}}d==(Hhb(),Ehb)&&vU(c,j[e])}for(i=new Tob(c);i.a<i.c.c.length;){h=Wv(Rob(i),9);rX(h,null);rX(h,f)}}pI(b)};var eC=Nkb(jAb,'InLayerConstraintProcessor',473);hI(474,1,eAb,R$);_.sc=function W$(a,b){var c,d,e,f,g,h;if(!Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))){return}for(h=new Tob(a.b);h.a<h.c.c.length;){f=Wv(Rob(h),9);if(f.g==(CX(),AX)){e=Wv(rJ(f,(eM(),GL)),65);this.c=Qlb(this.c,f.i.a-e.b);this.a=Nlb(this.a,f.i.a+f.j.a+e.c);this.d=Qlb(this.d,f.i.b-e.d);this.b=Nlb(this.b,f.i.b+f.j.b+e.a)}}for(g=new Tob(a.b);g.a<g.c.c.length;){f=Wv(Rob(g),9);if(f.g!=(CX(),AX)){switch(f.g.e){case 2:d=Wv(rJ(f,(Mjb(),vjb)),85);if(d==(Xib(),Tib)){f.i.a=this.c-10;Q$(f,new X$).A(new Z$(f));break}if(d==Vib){f.i.a=this.a+10;Q$(f,new _$).A(new b_(f));break}c=Wv(rJ(f,mib),140);if(c==(Hhb(),Ghb)){P$(f).A(new d_(f));f.i.b=this.d-10;break}if(c==Ehb){P$(f).A(new f_(f));f.i.b=this.b+10;break}break;default:throw new slb('The node type '+f.g+' is not supported by the '+lC);}}}};_.a=Vzb;_.b=Vzb;_.c=Uzb;_.d=Uzb;var lC=Nkb(jAb,'InteractiveExternalPortPositioner',474);hI(475,1,Tyb,X$);_.B=function Y$(a){return Wv(a,12).d.f};var fC=Nkb(jAb,'InteractiveExternalPortPositioner/lambda$0$Type',475);hI(476,1,Tyb,Z$);_.B=function $$(a){return S$(this.a,a)};var gC=Nkb(jAb,'InteractiveExternalPortPositioner/lambda$1$Type',476);hI(477,1,Tyb,_$);_.B=function a_(a){return Wv(a,12).c.f};var hC=Nkb(jAb,'InteractiveExternalPortPositioner/lambda$2$Type',477);hI(478,1,Tyb,b_);_.B=function c_(a){return T$(this.a,a)};var iC=Nkb(jAb,'InteractiveExternalPortPositioner/lambda$3$Type',478);hI(479,1,Tyb,d_);_.B=function e_(a){return U$(this.a,a)};var jC=Nkb(jAb,'InteractiveExternalPortPositioner/lambda$4$Type',479);hI(480,1,Tyb,f_);_.B=function g_(a){return V$(this.a,a)};var kC=Nkb(jAb,'InteractiveExternalPortPositioner/lambda$5$Type',480);hI(37,17,{37:1,3:1,23:1,17:1},f0);var h_,i_,j_,k_,l_,m_,n_,o_,p_,q_,r_,s_,t_,u_,v_,w_,x_,y_,z_,A_,B_,C_,D_,E_,F_,G_,H_,I_,J_,K_,L_,M_,N_,O_,P_,Q_,R_,S_,T_,U_,V_,W_,X_,Y_,Z_,$_,__,a0,b0,c0;var mC=Okb(jAb,'IntermediateProcessorStrategy',37,IF,g0);hI(503,1,eAb,k0);_.sc=function l0(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;nI(b,'Inverted port preprocessing',1);j=a.c;i=new Fnb(j,0);c=null;s=new GU;while(i.b<i.d.Y()){r=c;c=(Bxb(i.b<i.d.Y()),Wv(i.d.sb(i.c=i.b++),16));for(m=new Tob(s);m.a<m.c.c.length;){k=Wv(Rob(m),9);rX(k,r)}s.c=xv(UF,syb,1,0,4,1);for(n=new Tob(c.a);n.a<n.c.c.length;){k=Wv(Rob(n),9);if(k.g!=(CX(),AX)){continue}if(!MM(Wv(rJ(k,(eM(),TL)),28))){continue}for(q=pX(k,(djb(),ajb),(sN(),ZM)).mb();q.G();){o=Wv(q.H(),7);h=o.b;g=Wv(FU(h,xv(dB,gAb,12,h.c.length,0,1)),47);for(e=0,f=g.length;e<f;++e){d=g[e];h0(a,o,d,s)}}for(p=pX(k,bjb,rN).mb();p.G();){o=Wv(p.H(),7);h=o.e;g=Wv(FU(h,xv(dB,gAb,12,h.c.length,0,1)),47);for(e=0,f=g.length;e<f;++e){d=g[e];i0(a,o,d,s)}}}}for(l=new Tob(s);l.a<l.c.c.length;){k=Wv(Rob(l),9);rX(k,c)}pI(b)};var nC=Nkb(jAb,'InvertedPortProcessor',503);hI(481,1,eAb,m0);_.sc=function n0(a,b){nI(b,'Node and Port Label Placement and Node Sizing',1);GO((nW(),nW(),new wW(a,false)));pI(b)};var oC=Nkb(jAb,'LabelAndNodeSizeProcessor',481);hI(482,1,eAb,q0);_.sc=function r0(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;nI(b,'Label dummy insertions',1);m=new GU;k=Wv(rJ(a,(eM(),DL)),15).a;l=Wv(rJ(a,sL),59);for(o=new Tob(a.b);o.a<o.c.c.length;){n=Wv(Rob(o),9);for(q=new Tob(n.f);q.a<q.c.c.length;){p=Wv(Rob(q),7);for(h=new Tob(p.e);h.a<h.c.c.length;){g=Wv(Rob(h),12);if(g.c.f!=g.d.f&&ol(g.b,o0)){s=Do(g.b.c.length);c=new uX(a);sX(c,(CX(),yX));sJ(c,(Rib(),uib),g);sJ(c,Hib,s);sJ(c,TL,(KM(),FM));sJ(c,qib,g.c);sJ(c,rib,g.d);m.c[m.c.length]=c;i1(g,c);t=Wv(rJ(g,dM),15).a;if(t<0){t=0;sJ(g,dM,new llb(t))}r=Math.floor(t/2);for(e=new Tob(c.f);e.a<e.c.c.length;){d=Wv(Rob(e),7);d.i.b=r}f=c.j;i=new Fnb(g.b,0);while(i.b<i.d.Y()){j=(Bxb(i.b<i.d.Y()),Wv(i.d.sb(i.c=i.b++),33));if(gw(rJ(j,tL))===gw((EK(),AK))){if(l==(sK(),rK)||l==nK){f.a+=j.j.a+k;f.b=Nlb(f.b,j.j.b)}else{f.a=Nlb(f.a,j.j.a);f.b+=j.j.b+k}s.c[s.c.length]=j;vnb(i)}}if(l==(sK(),rK)||l==nK){f.a-=k;f.b+=k+t}else{f.b+=k+t}}}}}xU(a.b,m);pI(b)};var o0;var qC=Nkb(jAb,'LabelDummyInserter',482);hI(483,1,_zb,s0);_.D=function t0(a){return gw(rJ(Wv(a,33),(eM(),tL)))===gw((EK(),AK))};var pC=Nkb(jAb,'LabelDummyInserter/1',483);hI(484,1,eAb,w0);_.sc=function x0(a,b){var c,d,e,f,g,h,i,j,k,l,m;nI(b,'Label dummy removal',1);e=Wv(rJ(a,(eM(),DL)),15).a;h=Wv(rJ(a,sL),59);for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);j=new Fnb(f.a,0);while(j.b<j.d.Y()){i=(Bxb(j.b<j.d.Y()),Wv(j.d.sb(j.c=j.b++),9));if(i.g==(CX(),yX)){k=Wv(rJ(i,(Rib(),uib)),12);m=Wv(rJ(k,dM),15).a;c=new II(i.i);gw(rJ(i,pib))===gw((kP(),hP))&&(c.b+=m+e);d=new HI(i.j.a,i.j.b-m-e);l=Wv(rJ(i,Hib),20);h==(sK(),rK)||h==nK?v0(l,c,e,d,gw(rJ(i,pib))!==gw(gP)):u0(l,c,e,d);xU(k.b,l);c1(i,false);vnb(j)}}}pI(b)};var rC=Nkb(jAb,'LabelDummyRemover',484);hI(485,1,eAb,A0);_.sc=function B0(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;nI(b,'Label dummy switching',1);c=new GU;l=new GU;h=new GU;n=new GU;for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);for(k=new Tob(f.a);k.a<k.c.c.length;){j=Wv(Rob(k),9);if(j.g==(CX(),yX)){c.c[c.c.length]=j;h.c=xv(UF,syb,1,0,4,1);n.c=xv(UF,syb,1,0,4,1);p=j;do{p=Wv(Dm(Uh(iX(p))),12).c.f;p.g==zX&&(h.c[h.c.length]=p,true)}while(p.g==zX);s=j;do{s=Wv(Dm(Uh(mX(s))),12).d.f;s.g==zX&&(n.c[n.c.length]=s,true)}while(s.g==zX);i=h.c.length;o=n.c.length;if(i>o+1){m=(i+o)/2|0;vU(l,new RJ(j,(Cxb(m,h.c.length),Wv(h.c[m],9))))}else if(o>i+1){m=((o-i)/2|0)-1;vU(l,new RJ(j,(Cxb(m,n.c.length),Wv(n.c[m],9))))}}}}for(r=new Tob(l);r.a<r.c.c.length;){q=Wv(Rob(r),27);z0(Wv(q.a,9),Wv(q.b,9))}for(e=new Tob(c);e.a<e.c.c.length;){d=Wv(Rob(e),9);y0(d,new C0,(Rib(),rib));y0(d,new E0,qib)}pI(b)};var uC=Nkb(jAb,'LabelDummySwitcher',485);hI(486,1,Tyb,C0);_.B=function D0(a){return Wv(Dm(Uh(iX(Wv(a,9)))),12).c.f};var sC=Nkb(jAb,'LabelDummySwitcher/lambda$0$Type',486);hI(487,1,Tyb,E0);_.B=function F0(a){return Wv(Dm(Uh(mX(Wv(a,9)))),12).d.f};var tC=Nkb(jAb,'LabelDummySwitcher/lambda$1$Type',487);hI(488,1,eAb,G0);_.sc=function H0(a,b){nI(b,'Label management',1);iw(rJ(a,(bK(),aK)));pI(b)};var vC=Nkb(jAb,'LabelManagementProcessor',488);hI(489,1,eAb,S0);_.sc=function T0(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;i=Wv(rJ(a,(Mjb(),ojb)),115);nI(b,'Label side selection ('+i+')',1);j=(_b(a),new Vh(a));switch(i.e){case 0:L0(j);break;case 1:K0(j);break;case 2:O0(j);break;case 3:N0(j);break;case 4:R0(j);}for(h=new Tob(a.c);h.a<h.c.c.length;){g=Wv(Rob(h),16);for(d=new Tob(g.a);d.a<d.c.c.length;){c=Wv(Rob(d),9);for(n=new Tob(c.f);n.a<n.c.c.length;){l=Wv(Rob(n),7);for(f=new Tob(l.c);f.a<f.c.c.length;){e=Wv(Rob(f),33);gw(rJ(e,(Rib(),pib)))===gw((kP(),jP))&&sJ(e,pib,I0)}}if(c.g==(CX(),yX)){if(gw(rJ(c,(Rib(),pib)))===gw((kP(),gP))){k=Wv(rJ(c,uib),12);p=Wv(rJ(k,(eM(),dM)),15).a;o=c.j.b-Math.ceil(p/2);for(m=new Tob(c.f);m.a<m.c.c.length;){l=Wv(Rob(m),7);l.i.b=o}}}}}pI(b)};var I0;var xC=Nkb(jAb,'LabelSideSelector',489);hI(490,1,fyb,V0);_.$b=function W0(a,b){return U0(Wv(a,7),Wv(b,7))};var wC=Nkb(jAb,'LabelSideSelector/1',490);hI(495,1,eAb,Z0);_.sc=function $0(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;nI(b,'Layer constraint application',1);j=a.c;if(j.c.length==0){pI(b);return}f=(Cxb(0,j.c.length),Wv(j.c[0],16));g=Wv(yU(j,j.c.length-1),16);s=new sY(a);t=new sY(a);for(i=new Tob(j);i.a<i.c.c.length;){h=Wv(Rob(i),16);p=Wv(FU(h.a,xv(qB,Nzb,9,h.a.c.length,0,1)),51);for(m=0,o=p.length;m<o;++m){l=p[m];c=Wv(rJ(l,(Mjb(),vjb)),85);switch(c.e){case 1:rX(l,f);X0(l,false);break;case 2:rX(l,s);X0(l,true);break;case 3:rX(l,g);Y0(l);break;case 4:rX(l,t);Y0(l);}}}if(j.c.length>=2){k=true;q=(Cxb(1,j.c.length),Wv(j.c[1],16));for(n=new Tob(f.a);n.a<n.c.c.length;){l=Wv(Rob(n),9);if(gw(rJ(l,(Mjb(),vjb)))===gw((Xib(),Wib))){k=false;break}for(e=Uh(mX(l));Cm(e);){d=Wv(Dm(e),12);if(d.d.f.d==q){k=false;break}}if(!k){break}}if(k){p=Wv(FU(f.a,xv(qB,Nzb,9,f.a.c.length,0,1)),51);for(m=0,o=p.length;m<o;++m){l=p[m];rX(l,q)}BU(j,f)}}if(j.c.length>=2){k=true;r=Wv(yU(j,j.c.length-2),16);for(n=new Tob(g.a);n.a<n.c.c.length;){l=Wv(Rob(n),9);if(gw(rJ(l,(Mjb(),vjb)))===gw((Xib(),Wib))){k=false;break}for(e=Uh(iX(l));Cm(e);){d=Wv(Dm(e),12);if(d.c.f.d==r){k=false;break}}if(!k){break}}if(k){p=Wv(FU(g.a,xv(qB,Nzb,9,g.a.c.length,0,1)),51);for(m=0,o=p.length;m<o;++m){l=p[m];rX(l,r)}BU(j,g)}}j.c.length==1&&(Cxb(0,j.c.length),Wv(j.c[0],16)).a.c.length==0&&AU(j,0);s.a.c.length==0||(Fxb(0,j.c.length),fxb(j.c,0,s));t.a.c.length==0||(j.c[j.c.length]=t,true);pI(b)};var yC=Nkb(jAb,'LayerConstraintProcessor',495);hI(496,1,eAb,_0);_.sc=function a1(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;nI(b,'Layer size calculation',1);j=rAb;i=4.9E-324;for(g=new Tob(a.c);g.a<g.c.c.length;){f=Wv(Rob(g),16);h=f.c;h.a=0;h.b=0;if(f.a.c.length==0){continue}for(l=new Tob(f.a);l.a<l.c.c.length;){k=Wv(Rob(l),9);n=k.j;m=k.e;h.a=Nlb(h.a,n.a+m.b+m.c)}d=Wv(yU(f.a,0),9);o=d.i.b-d.e.d;e=Wv(yU(f.a,f.a.c.length-1),9);c=e.i.b+e.j.b+e.e.a;h.b=c-o;j=j<o?j:o;i=i>c?i:c}a.e.b=i-j;a.d.b-=j;pI(b)};var zC=Nkb(jAb,'LayerSizeAndGraphHeightCalculator',496);hI(497,1,eAb,b1);_.sc=function d1(a,b){var c,d,e,f,g;nI(b,'Edge joining',1);c=Ckb(Ixb(Xv(rJ(a,(Mjb(),gjb)))));for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);g=new Fnb(d.a,0);while(g.b<g.d.Y()){f=(Bxb(g.b<g.d.Y()),Wv(g.d.sb(g.c=g.b++),9));if(f.g==(CX(),zX)){c1(f,c);vnb(g)}}}pI(b)};var AC=Nkb(jAb,'LongEdgeJoiner',497);hI(498,1,eAb,e1);_.sc=function g1(a,b){var c,d,e,f,g,h,i,j,k,l,m,n;nI(b,'Edge splitting',1);if(a.c.c.length<=2){pI(b);return}f=new Fnb(a.c,0);g=(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),16));while(f.b<f.d.Y()){e=g;g=(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),16));for(i=new Tob(e.a);i.a<i.c.c.length;){h=Wv(Rob(i),9);for(k=new Tob(h.f);k.a<k.c.c.length;){j=Wv(Rob(k),7);for(d=new Tob(j.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);m=c.d;l=m.f.d;l!=e&&l!=g&&i1(c,(n=new uX(a),sX(n,(CX(),zX)),sJ(n,(Rib(),uib),c),sJ(n,(eM(),TL),(KM(),FM)),rX(n,g),n))}}}}pI(b)};var BC=Nkb(jAb,'LongEdgeSplitter',498);hI(499,1,eAb,k1);_.sc=function l1(a,b){var c,d,e,f,g,h,i,j;nI(b,'Node margin calculation',1);c=new rP((nW(),new wW(a,true)));oP(c);h=Wv(rJ(a,(Rib(),Jib)),15).a;for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);for(g=new Tob(d.a);g.a<g.c.c.length;){f=Wv(Rob(g),9);j1(f,h);i=f.e;j=Wv(rJ(f,Oib),65);i.b=Nlb(i.b,j.b);i.c=Nlb(i.c,j.c);i.a=Nlb(i.a,j.a);i.d=Nlb(i.d,j.d)}}pI(b)};var CC=Nkb(jAb,zzb,499);hI(491,1,eAb,q1);_.sc=function t1(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Node promotion heuristic',1);this.g=a;m1(this);this.q=Wv(rJ(a,(Mjb(),Bjb)),109);j=Wv(rJ(this.g,Cjb),24).a;e=new u1;switch(this.q.e){case 2:case 1:o1(this,e);break;case 3:this.q=(I1(),H1);o1(this,e);h=0;for(g=new Tob(this.a);g.a<g.c.c.length;){f=Wv(Rob(g),24);h=Plb(h,f.a)}if(h>this.j){this.q=B1;o1(this,e)}break;case 4:this.q=(I1(),H1);o1(this,e);i=0;for(d=new Tob(this.b);d.a<d.c.c.length;){c=Yv(Rob(d));i=Nlb(i,(Dxb(c),c))}if(i>this.k){this.q=E1;o1(this,e)}break;case 6:l=hw(Llb(this.f.length*j/100));o1(this,new w1(l));break;case 5:k=hw(Llb(this.d*j/100));o1(this,new y1(k));break;default:o1(this,e);}p1(this,a);pI(b)};_.d=0;_.e=0;_.i=0;_.j=0;_.k=0;_.n=0;var HC=Nkb(jAb,'NodePromotion',491);hI(492,1,Tyb,u1);_.B=function v1(a){return xkb(),xkb(),wkb};var DC=Nkb(jAb,'NodePromotion/lambda$0$Type',492);hI(493,1,Tyb,w1);_.B=function x1(a){return r1(this.a,a)};_.a=0;var EC=Nkb(jAb,'NodePromotion/lambda$1$Type',493);hI(494,1,Tyb,y1);_.B=function z1(a){return s1(this.a,a)};_.a=0;var FC=Nkb(jAb,'NodePromotion/lambda$2$Type',494);hI(109,17,{109:1,3:1,23:1,17:1},J1);var A1,B1,C1,D1,E1,F1,G1,H1;var GC=Okb(jAb,'NodePromotionStrategy',109,IF,K1);var L1;hI(500,1,eAb,R1);_.sc=function S1(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;nI(b,sAb,1);n=Wv(rJ(a,(eM(),uL)),122);for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);i=Wv(FU(d.a,xv(qB,Nzb,9,d.a.c.length,0,1)),51);for(g=0,h=i.length;g<h;++g){f=i[g];if(f.g!=(CX(),BX)){continue}if(n==(NK(),LK)){for(k=new Tob(f.f);k.a<k.c.c.length;){j=Wv(Rob(k),7);j.b.c.length==0||P1(j);j.e.c.length==0||Q1(j)}}else if(aw(rJ(f,(Rib(),uib)),12)){p=Wv(rJ(f,uib),12);q=Wv(nX(f,(sN(),rN)).mb().H(),7);r=Wv(nX(f,ZM).mb().H(),7);s=Wv(rJ(q,uib),7);t=Wv(rJ(r,uib),7);dW(p,t);eW(p,s);u=new II(r.f.i);u.a=MI(Bv(tv(qz,1),Fzb,10,0,[t.f.i,t.i,t.a])).a;QI(p.a,u);u=new II(q.f.i);u.a=MI(Bv(tv(qz,1),Fzb,10,0,[s.f.i,s.i,s.a])).a;QI(p.a,u)}else{if(f.f.c.length>=2){o=true;l=new Tob(f.f);c=Wv(Rob(l),7);while(l.a<l.c.c.length){m=c;c=Wv(Rob(l),7);if(!rb(rJ(m,uib),rJ(c,uib))){o=false;break}}}else{o=false}for(k=new Tob(f.f);k.a<k.c.c.length;){j=Wv(Rob(k),7);j.b.c.length==0||N1(j,o);j.e.c.length==0||O1(j,o)}}rX(f,null)}}pI(b)};var IC=Nkb(jAb,'NorthSouthPortPostprocessor',500);hI(501,1,eAb,X1);_.sc=function Y1(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;nI(b,sAb,1);o=new GU;u=new GU;for(j=new Tob(a.c);j.a<j.c.c.length;){i=Wv(Rob(j),16);q=-1;n=Wv(FU(i.a,xv(qB,Nzb,9,i.a.c.length,0,1)),51);for(l=0,m=n.length;l<m;++l){k=n[l];++q;if(!(k.g==(CX(),AX)&&MM(Wv(rJ(k,(eM(),TL)),28)))){continue}LM(Wv(rJ(k,(eM(),TL)),28))||W1(k);sJ(k,(Rib(),nib),k);o.c=xv(UF,syb,1,0,4,1);u.c=xv(UF,syb,1,0,4,1);c=new GU;t=new aJ;ml(t,nX(k,(sN(),$M)));U1(a,t,o,u,c);h=q;for(f=new Tob(o);f.a<f.c.c.length;){d=Wv(Rob(f),9);qX(d,h,i);++q;sJ(d,nib,k);g=Wv(yU(d.f,0),7);p=Wv(rJ(g,uib),7);Ckb(Ixb(Xv(rJ(p,(Mjb(),Djb)))))||Wv(rJ(d,oib),20).ib(k)}_I(t);for(s=nX(k,pN).mb();s.G();){r=Wv(s.H(),7);TI(t,r,t.a,t.a.a)}U1(a,t,u,null,c);for(e=new Tob(u);e.a<e.c.c.length;){d=Wv(Rob(e),9);qX(d,++q,i);sJ(d,nib,k);g=Wv(yU(d.f,0),7);p=Wv(rJ(g,uib),7);Ckb(Ixb(Xv(rJ(p,(Mjb(),Djb)))))||Wv(rJ(k,oib),20).ib(d)}c.c.length==0||sJ(k,Shb,c)}}pI(b)};var KC=Nkb(jAb,'NorthSouthPortPreprocessor',501);hI(502,1,fyb,Z1);_.$b=function $1(a,b){var c,d;return c=a.g,d=b.g,c!=d?c.e-d.e:a.k==b.k?0:c==(sN(),$M)?a.k-b.k:b.k-a.k};var JC=Nkb(jAb,'NorthSouthPortPreprocessor/lambda$0$Type',502);hI(504,1,eAb,_1);_.sc=function a2(a,b){var c,d,e,f,g,h;nI(b,'Removing partition constraint edges',1);for(d=new Tob(a.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);for(f=new Tob(c.a);f.a<f.c.c.length;){e=Wv(Rob(f),9);h=new Tob(e.f);while(h.a<h.c.c.length){g=Wv(Rob(h),7);Ckb(Ixb(Xv(rJ(g,(Rib(),Aib)))))&&Sob(h)}}}pI(b)};var LC=Nkb(jAb,'PartitionPostprocessor',504);hI(505,1,eAb,c2);_.sc=function d2(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Adding partition constraint edges',1);this.a=new GU;for(h=new Tob(a.b);h.a<h.c.c.length;){f=Wv(Rob(h),9);e=Wv(rJ(f,(eM(),ML)),24);b2(this,e.a).ib(f)}for(d=0;d<this.a.c.length-1;d++){for(g=Wv(yU(this.a,d),20).mb();g.G();){f=Wv(g.H(),9);k=new RX;PX(k,f);QX(k,(sN(),ZM));sJ(k,(Rib(),Aib),(xkb(),xkb(),wkb));for(j=Wv(yU(this.a,d+1),20).mb();j.G();){i=Wv(j.H(),9);l=new RX;PX(l,i);QX(l,rN);sJ(l,Aib,(null,wkb));c=new hW;sJ(c,Aib,(null,wkb));sJ(c,(eM(),ZL),Elb(20));dW(c,k);eW(c,l)}}}this.a=null;pI(b)};var MC=Nkb(jAb,'PartitionPreprocessor',505);hI(506,1,eAb,f2);_.sc=function g2(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;nI(b,'Port distribution',1);c=jW(a);n=0;k=0;for(e=0,g=c.length;e<g;++e){d=c[e];for(i=0,j=d.length;i<j;++i){h=d[i];h.k=k++;for(m=new Tob(h.f);m.a<m.c.c.length;){l=Wv(Rob(m),7);l.k=n++}}}for(f=new Tob(a.c);f.a<f.c.c.length;){d=Wv(Rob(f),16);e2(d)}p=Wv(rJ(a,(Rib(),Gib)),154);o=wvb(p,1)!=0?new P9(xv(lw,tAb,26,n,12,1)):new M9(xv(lw,tAb,26,n,12,1));Z8(o,c);pI(b)};var NC=Nkb(jAb,'PortDistributionProcessor',506);hI(507,1,eAb,h2);_.sc=function i2(a,b){var c,d,e,f,g;nI(b,'Port order processing',1);g=new k2;for(d=new Tob(a.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);for(f=new Tob(c.a);f.a<f.c.c.length;){e=Wv(Rob(f),9);MM(Wv(rJ(e,(eM(),TL)),28))&&Gpb(e.f,g)}}pI(b)};var PC=Nkb(jAb,'PortListSorter',507);hI(508,1,fyb,k2);_.$b=function l2(a,b){return j2(Wv(a,7),Wv(b,7))};var OC=Nkb(jAb,'PortListSorter/PortComparator',508);hI(509,1,eAb,n2);_.sc=function o2(a,b){var c,d,e,f,g;nI(b,'Port side processing',1);for(g=new Tob(a.b);g.a<g.c.c.length;){e=Wv(Rob(g),9);m2(e)}for(d=new Tob(a.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);for(f=new Tob(c.a);f.a<f.c.c.length;){e=Wv(Rob(f),9);m2(e)}}pI(b)};var QC=Nkb(jAb,'PortSideProcessor',509);hI(510,1,eAb,q2);_.sc=function r2(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Restoring reversed edges',1);for(h=new Tob(a.c);h.a<h.c.c.length;){g=Wv(Rob(h),16);for(j=new Tob(g.a);j.a<j.c.c.length;){i=Wv(Rob(j),9);for(l=new Tob(i.f);l.a<l.c.c.length;){k=Wv(Rob(l),7);f=Wv(FU(k.e,xv(dB,gAb,12,k.e.c.length,0,1)),47);for(d=0,e=f.length;d<e;++d){c=f[d];Ckb(Ixb(Xv(rJ(c,(Rib(),Iib)))))&&cW(c,false)}}}}pI(b)};var RC=Nkb(jAb,'ReversedEdgeRestorer',510);hI(511,1,eAb,x2);_.sc=function y2(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J;nI(b,'Sausage Folding',1);this.b=Wv(rJ(a,(Rib(),Jib)),15).a;this.a=this.b*Wv(rJ(a,(Mjb(),Ejb)),15).a;o=t2(this,a);n=a.c.c.length;p=u2(this,a);G=n*p;e=Wv(rJ(a,(eM(),sL)),59);e==(sK(),oK)||e==pK||e==qK?(d=Wv(rJ(a,Rhb),15).a):(d=1/Wv(rJ(a,Rhb),15).a);c=G/o;if(d>c){pI(b);return}D=0;f=rAb;do{++D;c=G/D/(o*D);m=f;f=c-d<=0?0-(c-d):c-d}while(c>d);m<f&&--D;B=n/(1>D?1:D)|0;j=B;u=B;J=true;while(j<n){l=Wv(yU(a.c,j),16);C=true;s=null;t=null;K:for(I=new Tob(l.a);I.a<I.c.c.length;){H=Wv(Rob(I),9);for(h=Uh(iX(H));Cm(h);){g=Wv(Dm(h),12);if(!!s&&s!=H){C=false;break K}s=H;F=g.c.f;if(!!t&&t!=F){C=false;break K}t=F}}if(J&&C){u=0;J=false}if(j!=u){v=Wv(yU(a.c,u),16);for(r=new Tob(Ao(l.a));r.a<r.c.c.length;){q=Wv(Rob(r),9);qX(q,v.a.c.length,v);if(u==0){for(h=new Tob(Ao(iX(q)));h.a<h.c.c.length;){g=Wv(Rob(h),12);cW(g,true);sJ(a,cib,(xkb(),xkb(),wkb));v2(a,g);i=new GU;s2(a,g.c,g,i);for(A=new Tob(i);A.a<A.c.c.length;){w=Wv(Rob(A),9);qX(w,v.a.c.length-1,v)}}}}}u>=B&&(J=true);++u;++j}k=new Fnb(a.c,0);while(k.b<k.d.Y()){l=(Bxb(k.b<k.d.Y()),Wv(k.d.sb(k.c=k.b++),16));l.a.c.length==0&&vnb(k)}pI(b)};_.a=0;_.b=0;var SC=Nkb(jAb,'SausageFolding',511);hI(512,1,eAb,A2);_.sc=function B2(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;nI(b,'Self-loop processing',1);c=new GU;for(k=new Tob(a.c);k.a<k.c.c.length;){j=Wv(Rob(k),16);c.c=xv(UF,syb,1,0,4,1);for(m=new Tob(j.a);m.a<m.c.c.length;){l=Wv(Rob(m),9);for(o=new Tob(l.f);o.a<o.c.c.length;){n=Wv(Rob(o),7);i=Wv(FU(n.e,xv(dB,gAb,12,n.e.c.length,0,1)),47);for(g=0,h=i.length;g<h;++g){f=i[g];if(f.c.f!=f.d.f){continue}p=f.c;r=f.d;q=p.g;s=r.g;(q==(sN(),$M)||q==pN)&&s==rN?cW(f,false):q==pN&&s==$M?cW(f,false):q==ZM&&s!=ZM&&cW(f,false);q==ZM&&s==rN?vU(c,z2(a,f,r,p)):q==rN&&s==ZM&&vU(c,z2(a,f,p,r))}}}for(e=new Tob(c);e.a<e.c.c.length;){d=Wv(Rob(e),9);rX(d,j)}}pI(b)};var TC=Nkb(jAb,'SelfLoopProcessor',512);hI(513,1,eAb,H2);_.sc=function I2(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;nI(b,'Spline SelfLoop positioning',1);k=Wv(rJ(a,(Mjb(),Jjb)),153);for(j=new Tob(a.c);j.a<j.c.c.length;){i=Wv(Rob(j),16);for(m=new Tob(i.a);m.a<m.c.c.length;){l=Wv(Rob(m),9);g=Wv(rJ(l,(Rib(),Nib)),20);h=new GU;for(e=g.mb();e.G();){c=Wv(e.H(),75);ceb(c);if((n=pr(c.g),Ue(n,c.i),n).a.Y()==0){h.c[h.c.length]=c}else{G2(c);c.g.a.Y()==0||C2(c)}}switch(k.e){case 0:o=new Q2(l);P2(o);N2(o,h);break;case 2:for(f=new Tob(h);f.a<f.c.c.length;){c=Wv(Rob(f),75);aeb(c,(Ieb(),meb),true)}break;case 1:for(d=new Tob(h);d.a<d.c.c.length;){c=Wv(Rob(d),75);aeb(c,(Ieb(),meb),true)}}switch(k.e){case 0:case 1:F2(g);break;case 2:E2(g);}}}pI(b)};var ZC=Nkb(jAb,'SplineSelfLoopPositioner',513);hI(515,1,{},Q2);var WC=Nkb(jAb,'SplineSelfLoopPositioner/DistributedLoopSidesCalculator',515);hI(516,1,{},$2);_.d=true;var VC=Nkb(jAb,'SplineSelfLoopPositioner/DistributedLoopSidesCalculator/SortedLoopSides',516);hI(116,1,{116:1},_2);_.a=0;_.b=0;var UC=Nkb(jAb,'SplineSelfLoopPositioner/DistributedLoopSidesCalculator/SortedLoopSides/SizeOfSide',116);hI(318,1,{},g3);var a3;var XC=Nkb(jAb,'SplineSelfLoopPositioner/PortReadder',318);hI(514,1,fyb,i3);_.$b=function j3(a,b){return h3(Wv(a,75),Wv(b,75))};var YC=Nkb(jAb,'SplineSelfLoopPositioner/TextWidthComparator',514);hI(517,1,eAb,l3);_.sc=function o3(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s;nI(b,'Spline SelfLoop pre-processing.',1);k=new Wub;for(m=new Tob(a.b);m.a<m.c.c.length;){l=Wv(Rob(m),9);k3(l);k.a.Q();for(h=Uh(mX(l));Cm(h);){f=Wv(Dm(h),12);bW(f)&&(n=k.a.db(f,k),n==null)}for(g=(o=(new Snb(k.a)).a.bb().mb(),new Ynb(o));g.a.G();){f=(i=Wv(g.a.H(),21),Wv(i.yb(),12));r=f.c.g;s=f.d.g;(r==(sN(),$M)&&(s==ZM||s==pN)||r==ZM&&s==pN||r==pN&&s==rN||r==rN&&(s==$M||s==ZM))&&cW(f,false)}c=n3(k,l);sJ(l,(Rib(),Nib),c);if(!LM(Wv(rJ(l,(eM(),TL)),28))){q=new vtb;for(e=new Tob(c);e.a<e.c.c.length;){d=Wv(Rob(e),75);Ue(q,Zdb(d));Ue(q,d.i)}j=new Fnb(l.f,0);while(j.b<j.d.Y()){p=(Bxb(j.b<j.d.Y()),Wv(j.d.sb(j.c=j.b++),7));q.a.R(p)&&vnb(j)}}}pI(b)};var $C=Nkb(jAb,'SplineSelfLoopPreProcessor',517);hI(518,1,eAb,u3);_.sc=function v3(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I;nI(b,'Spline SelfLoop routing',1);D=new I3;for(m=new Tob(a.c);m.a<m.c.c.length;){l=Wv(Rob(m),16);for(s=new Tob(l.a);s.a<s.c.c.length;){r=Wv(Rob(s),9);u=r.f;n=new Wub;for(d=Wv(rJ(r,(Rib(),Nib)),20).mb();d.G();){c=Wv(d.H(),75);Ue(n,c.a)}v=new GU;for(g=(t=(new Snb(n.a)).a.bb().mb(),new Ynb(t));g.a.G();){f=(h=Wv(g.a.H(),21),Wv(h.yb(),12));B=f.c;G=f.d;k=new Tob(f.c.f.f);A=0;F=0;i=0;j=0;while(i<2){e=Wv(Rob(k),7);if(B==e){A=j;++i}if(G==e){F=j;++i}++j}w=Wv(rJ(f,Mib),60);C=w==(Ieb(),neb)||w==keb?u.c.length-(F-A<0?-(F-A):F-A)+1:F-A<0?-(F-A):F-A;vU(v,new G3(A,F,C,w,f))}Gpb(v,D);p=new vtb;o=new Tob(v);if(o.a<o.c.c.length){q=t3(Wv(Rob(o),195),p);while(o.a<o.c.c.length){Afb(q,t3(Wv(Rob(o),195),p))}sJ(r,Oib,(H=new DP,I=new Bfb(r.j.a,r.j.b),H.d=Nlb(0,I.d-q.d),H.b=Nlb(0,I.b-q.b),H.a=Nlb(0,q.a-I.a),H.c=Nlb(0,q.c-I.c),H))}}}pI(b)};var fD=Nkb(jAb,'SplineSelfLoopRouter',518);hI(91,1,{91:1},w3);_.w=function x3(){return this.b+': '+this.d+' -> '+this.a+' '+zc(this.c)};_.a=0;_.b=0;_.d=0;var cD=Nkb(jAb,'SplineSelfLoopRouter/LoopPadding',91);hI(521,1,_zb,z3);_.D=function A3(a){return y3(this,Wv(a,91))};_.a=0;_.c=0;var _C=Nkb(jAb,'SplineSelfLoopRouter/LoopPadding/EnclosingPredicate',521);hI(520,1,fyb,C3);_.$b=function D3(a,b){return B3(Wv(a,91),Wv(b,91))};var aD=Nkb(jAb,'SplineSelfLoopRouter/LoopPadding/MarginComparator',520);hI(196,1,_zb,E3);_.D=function F3(a){return Wv(a,91).c==this.a};var bD=Nkb(jAb,'SplineSelfLoopRouter/LoopPadding/PortSidePredicate',196);hI(195,1,{195:1},G3);_.c=0;_.d=0;_.e=0;var eD=Nkb(jAb,'SplineSelfLoopRouter/SelfLoopEdge',195);hI(519,1,fyb,I3);_.$b=function J3(a,b){return H3(Wv(a,195),Wv(b,195))};var dD=Nkb(jAb,'SplineSelfLoopRouter/SelfLoopEdge/StepSizeComparator',519);hI(82,25,{25:1,82:1},L3);_.vc=function M3(){var a,b,c,d;for(b=WI(this.a,0);b.b!=b.d.c;){a=Wv(_ub(b),10);a.a=this.j.d}for(d=WI(this.c,0);d.b!=d.d.c;){c=Wv(_ub(d),10);c.a=this.j.d}};_.wc=function N3(){return this.b};_.xc=function O3(){return this.e};_.w=function P3(){return Ze(new Snb(this.d.a))};_.b=0;_.e=0;var gD=Nkb(vAb,'CLEdge',82);hI(93,25,{25:1,93:1},Q3);_.vc=function R3(){this.b.i.a=this.j.d+this.b.e.b};_.wc=function S3(){if(this.b.g==(CX(),xX)){return 0}return this.a};_.xc=function T3(){if(this.b.g==(CX(),xX)){return 0}return this.c};_.w=function U3(){return xb(rJ(this.b,(Rib(),uib)))};_.a=0;_.c=0;var hD=Nkb(vAb,'CLNode',93);hI(175,17,{175:1,3:1,23:1,17:1},Y3);var V3,W3;var iD=Okb(vAb,'ConstraintCalculationStrategy',175,IF,Z3);var $3;hI(125,17,{125:1,3:1,23:1,17:1},h4);var a4,b4,c4,d4,e4,f4;var jD=Okb(vAb,'GraphCompactionStrategy',125,IF,i4);var j4;hI(455,1,eAb,o4);_.sc=function p4(a,b){var c,d,e;d=Wv(rJ(a,(Mjb(),Fjb)),125);if(d==(g4(),e4)){return}nI(b,'Horizontal Compaction',1);this.a=a;e=new Q4;c=new rS(P4(e,a));pS(c,this.b);switch(Wv(rJ(a,Gjb),175).e){case 1:nS(c,l4);break;default:nS(c,(aS(),$R));}switch(d.e){case 1:hS(c);break;case 2:hS(gS(c,(sK(),pK)));break;case 3:hS(bS(gS(hS(c),(sK(),pK))));break;case 4:hS(bS(oS(gS(hS(c),(sK(),pK)),new H4)));break;case 5:hS(mS(c,m4));}gS(c,(sK(),oK));c.e=true;L4(e);pI(b)};var l4,m4;var sD=Nkb(vAb,'HorizontalGraphCompactor',455);hI(462,1,{},q4);_.tc=function r4(a,b){var c,d,e;if(aw(a,82)&&aw(b,82)&&!sr(or(Wv(a,82).d,Wv(b,82).d))){return 0}c=null;aw(a,93)&&(c=Wv(a,93).b);d=null;aw(b,93)&&(d=Wv(b,93).b);if(!!c&&c.g==(CX(),xX)||!!d&&d.g==(CX(),xX)){return 0}e=Wv(rJ(this.a.a,(Rib(),Kib)),134);return Vjb(e,c?c.g:(CX(),zX),d?d.g:(CX(),zX))};_.uc=function s4(a,b){if(aw(a,82)&&aw(b,82)&&!sr(or(Wv(a,82).d,Wv(b,82).d))){return 1}return Qlb(a.xc(),b.xc())};var kD=Nkb(vAb,'HorizontalGraphCompactor/1',462);hI(456,317,{},u4);_.Dc=function v4(a){var b,c,d;this.b=a;ES(this,new z4,this.a);ES(this,new B4,this.a);b=Uzb;for(d=new Tob(this.b.a.b);d.a<d.c.c.length;){c=Wv(Rob(d),25);if(aw(c,93)&&Wv(c,93).b.g==(CX(),xX)){continue}b=Qlb(b,Ixb(w4(this.a,c)))}b==Uzb&&(b=0);ES(this,new D4,new F4(b))};var qD=Nkb(vAb,'HorizontalGraphCompactor/EdgeAwareScanlineConstraintCalculation',456);hI(457,1,Tyb,x4);_.B=function y4(a){return w4(this,a)};var lD=Nkb(vAb,'HorizontalGraphCompactor/EdgeAwareScanlineConstraintCalculation/lambda$0$Type',457);hI(458,1,_zb,z4);_.D=function A4(a){return aw(Wv(a,25),82)};var mD=Nkb(vAb,'HorizontalGraphCompactor/EdgeAwareScanlineConstraintCalculation/lambda$1$Type',458);hI(459,1,_zb,B4);_.D=function C4(a){return aw(Wv(a,25),93)};var nD=Nkb(vAb,'HorizontalGraphCompactor/EdgeAwareScanlineConstraintCalculation/lambda$2$Type',459);hI(460,1,_zb,D4);_.D=function E4(a){return true};var oD=Nkb(vAb,'HorizontalGraphCompactor/EdgeAwareScanlineConstraintCalculation/lambda$3$Type',460);hI(461,1,Tyb,F4);_.B=function G4(a){return this.a};_.a=0;var pD=Nkb(vAb,'HorizontalGraphCompactor/EdgeAwareScanlineConstraintCalculation/lambda$4$Type',461);hI(463,1,Tyb,H4);_.B=function I4(a){return n4(),xkb(),uS(Wv(Wv(a,27).a,25).n,Wv(Wv(a,27).b,59))?vkb:wkb};var rD=Nkb(vAb,'HorizontalGraphCompactor/lambda$0$Type',463);hI(553,1,{},Q4);_.c=false;var tD=Nkb(vAb,'LGraphToCGraphTransformer',553);hI(552,1,{},U4);_.Cc=function V4(a){var b,c,d,e,f;this.a=a;this.d=new l7;this.c=xv(UD,syb,61,this.a.a.a.c.length,0,1);this.b=0;for(c=new Tob(this.a.a.a);c.a<c.c.c.length;){b=Wv(Rob(c),78);b.d=this.b;f=x7(z7(y7(new A7,this.b),b),this.d);this.c[this.b]=f;++this.b}T4(this);S4(this);R4(this);F7(W7(this.d),new sI);for(e=new Tob(this.a.a.b);e.a<e.c.c.length;){d=Wv(Rob(e),25);d.r=this.c[d.f.d].e+d.g.a;d.j.d=d.r}};_.b=0;var uD=Nkb(vAb,'NetworkSimplexCompaction',552);hI(142,1,{142:1,23:1},X4);_.F=function Y4(a){return W4(this,Wv(a,142))};_.c=false;_.d=true;_.i=0;_.j=0;_.k=0;_.n=0;var vD=Nkb(vAb,'VerticalSegment',142);hI(586,1,{},_4);_.e=false;var wD=Nkb(wAb,'AllCrossingsCounter',586);hI(339,1,{});var xD=Nkb(wAb,'BetweenLayerEdgeAllCrossingsCounter',339);hI(613,1,{},k5);_.c=0;_.e=0;_.i=0;var AD=Nkb(wAb,'BetweenLayerEdgeTwoNodeCrossingsCounter',613);hI(284,1,{284:1},r5);_.w=function s5(){return 'AdjacencyList [node='+this.d+', adjacencies= '+this.a+']'};_.b=0;_.c=0;_.f=0;var zD=Nkb(wAb,'BetweenLayerEdgeTwoNodeCrossingsCounter/AdjacencyList',284);hI(128,1,{128:1,23:1},v5);_.F=function w5(a){return t5(this,Wv(a,128))};_.w=function x5(){return 'Adjacency [position='+this.c+', cardinality='+this.a+', currentCardinality='+this.b+']'};_.a=0;_.b=0;_.c=0;var yD=Nkb(wAb,'BetweenLayerEdgeTwoNodeCrossingsCounter/AdjacencyList/Adjacency',128);hI(610,339,{},y5);_.Gc=function z5(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,ab,bb,cb,db,eb,fb,gb,hb,ib,jb,kb,lb,mb,nb;eb=0;for(I=0,L=a.length;I<L;++I){G=a[I];if(LM(Wv(rJ(G,(eM(),TL)),28))){for(U=new Tob(G.f);U.a<U.c.c.length;){T=Wv(Rob(U),7);W=0;for(g=new Tob(T.e);g.a<g.c.c.length;){f=Wv(Rob(g),12);G.d!=f.d.f.d&&++W}W>0&&(this.a[T.k]=eb++)}}else{N=0;for(U=new Tob(G.f);U.a<U.c.c.length;){T=Wv(Rob(U),7);for(g=new Tob(T.e);g.a<g.c.c.length;){f=Wv(Rob(g),12);G.d!=f.d.f.d&&++N}this.a[T.k]=eb}N>0&&++eb}}jb=0;for(J=0,M=b.length;J<M;++J){G=b[J];if(LM(Wv(rJ(G,(eM(),TL)),28))){O=0;for(U=new Tob(G.f);U.a<U.c.c.length;){T=Wv(Rob(U),7);if(T.g==(sN(),$M)){for(g=new Tob(T.b);g.a<g.c.c.length;){f=Wv(Rob(g),12);if(G.d!=f.c.f.d){++O;break}}}else{break}}Q=0;X=new Fnb(G.f,G.f.c.length);while(X.b>0){T=(Bxb(X.b>0),Wv(X.a.sb(X.c=--X.b),7));W=0;for(g=new Tob(T.b);g.a<g.c.c.length;){f=Wv(Rob(g),12);G.d!=f.c.f.d&&++W}if(W>0){if(T.g==(sN(),$M)){this.a[T.k]=jb;++jb}else{this.a[T.k]=jb+O+Q;++Q}}}jb+=Q}else{N=0;for(U=new Tob(G.f);U.a<U.c.c.length;){T=Wv(Rob(U),7);for(g=new Tob(T.b);g.a<g.c.c.length;){f=Wv(Rob(g),12);G.d!=f.c.f.d&&++N}this.a[T.k]=jb}N>0&&++jb}}V=new ntb;p=new vtb;for(H=0,K=a.length;H<K;++H){G=a[H];for(hb=new Tob(G.f);hb.a<hb.c.c.length;){gb=Wv(Rob(hb),7);for(g=new Tob(gb.e);g.a<g.c.c.length;){f=Wv(Rob(g),12);lb=f.d;if(G.d!=lb.f.d){fb=Wv(re(Ktb(V.d,gb)),204);kb=Wv(re(Ktb(V.d,lb)),204);if(!fb&&!kb){o=new B5;p.a.db(o,p);QI(o.a,f);QI(o.e,gb);Ltb(V.d,gb,o);QI(o.e,lb);Ltb(V.d,lb,o)}else if(!fb){QI(kb.a,f);QI(kb.e,gb);Ltb(V.d,gb,kb)}else if(!kb){QI(fb.a,f);QI(fb.e,lb);Ltb(V.d,lb,fb)}else if(fb==kb){QI(fb.a,f)}else{QI(fb.a,f);for(S=WI(kb.e,0);S.b!=S.d.c;){R=Wv(_ub(S),7);Ltb(V.d,R,fb)}Ue(fb.a,kb.a);Ue(fb.e,kb.e);p.a.eb(kb)!=null}}}}}q=Wv(Ye(p,xv(CD,{675:1,3:1,5:1,6:1},204,p.a.Y(),0,1)),675);F=a[0].d;db=b[0].d;for(m=0,n=q.length;m<n;++m){l=q[m];l.f=eb;l.g=jb;for(U=WI(l.e,0);U.b!=U.d.c;){T=Wv(_ub(U),7);Y=this.a[T.k];if(T.f.d==F){if(Y<l.f){l.f=Y;l.b=txb(T)}Y>l.c&&(l.c=Y)}else if(T.f.d==db){Y<l.g&&(l.g=Y);Y>l.d&&(l.d=Y)}}}ipb(q,0,q.length,(hsb(),hsb(),gsb));ib=xv(mw,Yyb,26,q.length,12,1);c=xv(mw,Yyb,26,jb+1,12,1);for(s=0;s<q.length;s++){ib[s]=q[s].g;c[ib[s]]=1}e=0;for(t=0;t<c.length;t++){c[t]==1?(c[t]=e):--e}Z=0;for(u=0;u<ib.length;u++){ib[u]+=c[ib[u]];Z=Plb(Z,ib[u]+1)}k=1;while(k<Z){k*=2}nb=2*k-1;k-=1;mb=xv(mw,Yyb,26,nb,12,1);d=0;for(i=0,j=ib.length;i<j;++i){h=ib[i];w=h+k;++mb[w];while(w>0){w%2>0&&(d+=mb[w+1]);w=(w-1)/2|0;++mb[w]}}D=xv(BD,syb,158,q.length*2,0,1);for(v=0;v<q.length;v++){D[2*v]=new E5(q[v],q[v].f,q[v].c,0);D[2*v+1]=new E5(q[v],q[v].c,q[v].f,1)}ipb(D,0,D.length,(null,gsb));P=0;for(B=0,C=D.length;B<C;++B){A=D[B];switch(A.d){case 0:++P;break;case 1:--P;d+=P;}}cb=xv(BD,syb,158,q.length*2,0,1);for(r=0;r<q.length;r++){cb[2*r]=new E5(q[r],q[r].g,q[r].d,0);cb[2*r+1]=new E5(q[r],q[r].d,q[r].g,1)}ipb(cb,0,cb.length,(null,gsb));P=0;for(ab=0,bb=cb.length;ab<bb;++ab){$=cb[ab];switch($.d){case 0:++P;break;case 1:--P;d+=P;}}return d};var DD=Nkb(wAb,'BetweenLayerHyperedgeAllCrossingsCounter',610);hI(204,1,{204:1,23:1},B5);_.F=function C5(a){return A5(this,Wv(a,204))};_.b=0;_.c=0;_.d=0;_.f=0;_.g=0;var CD=Nkb(wAb,'BetweenLayerHyperedgeAllCrossingsCounter/Hyperedge',204);hI(158,1,{158:1,23:1},E5);_.F=function F5(a){return D5(this,Wv(a,158))};_.b=0;_.c=0;_.d=0;var BD=Nkb(wAb,'BetweenLayerHyperedgeAllCrossingsCounter/HyperedgeCorner',158);hI(611,339,{},H5);_.Gc=function J5(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B;B=0;f=0;h=a[0].d;u=b[0].d;for(k=0,m=b.length;k<m;++k){i=b[k];if(LM(Wv(rJ(i,(eM(),TL)),28))){o=0;for(r=new Tob(i.f);r.a<r.c.c.length;){q=Wv(Rob(r),7);if(q.g==(sN(),$M)){for(e=new Tob(q.b);e.a<e.c.c.length;){d=Wv(Rob(e),12);if(d.c.f.d==h){++o;break}}}else{break}}p=0;t=new Fnb(i.f,i.f.c.length);while(t.b>0){q=(Bxb(t.b>0),Wv(t.a.sb(t.c=--t.b),7));s=0;for(e=new Tob(q.b);e.a<e.c.c.length;){d=Wv(Rob(e),12);d.c.f.d==h&&++s}if(s>0){if(q.g==(sN(),$M)){this.a[q.k]=B;++B}else{this.a[q.k]=B+o+p;++p}f+=s}}B+=p}else{n=0;for(r=new Tob(i.f);r.a<r.c.c.length;){q=Wv(Rob(r),7);for(e=new Tob(q.b);e.a<e.c.c.length;){d=Wv(Rob(e),12);d.c.f.d==h&&++n}this.a[q.k]=B}if(n>0){++B;f+=n}}}v=xv(mw,Yyb,26,f,12,1);g=0;for(j=0,l=a.length;j<l;++j){i=a[j];if(LM(Wv(rJ(i,(eM(),TL)),28))){for(r=new Tob(i.f);r.a<r.c.c.length;){q=Wv(Rob(r),7);w=g;for(e=new Tob(q.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);A=d.d;A.f.d==u&&K5(v,w,g++,this.a[A.k])}}}else{w=g;for(r=new Tob(i.f);r.a<r.c.c.length;){q=Wv(Rob(r),7);for(e=new Tob(q.e);e.a<e.c.c.length;){d=Wv(Rob(e),12);A=d.d;A.f.d==u&&K5(v,w,g++,this.a[A.k])}}}}c=G5(B,f,v);return c};var ED=Nkb(wAb,'BetweenLayerStraightEdgeAllCrossingsCounter',611);hI(338,1,{},N5);_.b=0;_.e=false;var FD=Nkb(wAb,'CrossingMatrixFiller',338);hI(447,1,eAb,$5);_.sc=function _5(a,b){var c,d,e,f;nI(b,'Greedy switch crossing reduction',1);this.e=Wv(rJ(a,(Mjb(),tjb)),110);c=a.c.c.length;if(c<2||this.e==(zhb(),rhb)){pI(b);return}Q5(this,a);this.e.b?(this.e.a?R5(this):Z5(this),d=P5(this),e=this.e.a?this.c:Z4(this.b,this.d),this.i=!this.i,this.d=this.g,this.e.a?R5(this):Z5(this),f=this.e.a?this.c:Z4(this.b,this.d),e<=f&&S5(this,d),undefined):this.e.a?R5(this):Z5(this);T5(this,this.a);pI(b)};_.c=0;_.i=true;var GD=Nkb(wAb,'GreedySwitchProcessor',447);hI(340,1,{},k6);var HD=Nkb(wAb,'InLayerEdgeAllCrossingsCounter',340);hI(614,340,{},r6);_.b=0;_.d=0;var JD=Nkb(wAb,'InLayerEdgeTwoNodeCrossingCounter',614);hI(226,1,{226:1,23:1},t6);_.F=function u6(a){return s6(this,Wv(a,226))};_.w=function v6(){return 'ComparableEdgeAndPort [port='+this.b+', edge='+this.a+', portPosition='+this.c+']'};_.c=0;var ID=Nkb(wAb,'InLayerEdgeTwoNodeCrossingCounter/ComparableEdgeAndPort',226);hI(612,1,{},F6);_.e=true;_.f=0;_.g=0;_.k=false;var KD=Nkb(wAb,'NorthSouthEdgeAllCrossingsCounter',612);hI(615,1,{},R6);_.b=0;_.d=0;_.e=false;var LD=Nkb(wAb,'NorthSouthEdgeNeighbouringNodeCrossingsCounter',615);hI(143,1,Oyb,U6);_.mb=function V6(){return T6(this)};_.b=0;var ND=Nkb(wAb,'PortIterable',143);hI(344,1,Ayb,W6);_.H=function Y6(){return Wv(Dnb(this.a),7)};_.G=function X6(){return this.a.b>0};_.I=function Z6(){throw new Hmb};var MD=Nkb(wAb,'PortIterable/1',344);hI(336,1,{},b7);var OD=Nkb(wAb,'SwitchDecider',336);hI(89,1,{89:1},d7);_.w=function e7(){return 'NEdge[id='+this.b+' w='+this.f+' d='+this.a+']'};_.a=1;_.b=0;_.e=false;_.f=0;var QD=Nkb(yAb,'NEdge',89);hI(157,1,{},k7);var PD=Nkb(yAb,'NEdge/NEdgeBuilder',157);hI(278,1,{},l7);var RD=Nkb(yAb,'NGraph',278);hI(61,1,{61:1},n7);_.b=0;_.d=-1;_.e=0;_.i=-1;_.j=false;var UD=Nkb(yAb,'NNode',61);hI(333,13,bAb,q7);_.rb=function r7(a,b){++this.d;Fxb(a,this.c.length);fxb(this.c,a,b)};_.ib=function s7(a){return o7(this,a)};_.jb=function t7(a){++this.d;return xU(this,a)};_.Q=function u7(){++this.d;this.c=xv(UF,syb,1,0,4,1)};_.vb=function v7(a){++this.d;return AU(this,a)};_.nb=function w7(a){return p7(this,a)};var SD=Nkb(yAb,'NNode/ChangeAwareArrayList',333);hI(199,1,{},A7);var TD=Nkb(yAb,'NNode/NNodeBuilder',199);hI(595,1,{},V7);_.a=false;_.f=$xb;_.j=0;var VD=Nkb(yAb,'NetworkSimplex',595);hI(193,17,{180:1,193:1,3:1,23:1,17:1},$7);_.rc=function _7(){switch(this.e){case 0:return new g8;case 1:return new m8;default:throw new slb('No implementation is available for the cycle breaker '+(this.d!=null?this.d:''+this.e));}};var X7,Y7;var WD=Okb(AAb,'CycleBreakingStrategy',193,IF,a8);var b8;hI(539,1,BAb,g8);_.qc=function h8(a){return d8};_.sc=function i8(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J;nI(b,'Greedy cycle removal',1);r=a.b;J=r.c.length;this.a=xv(mw,Yyb,26,J,12,1);this.c=xv(mw,Yyb,26,J,12,1);this.b=xv(mw,Yyb,26,J,12,1);h=0;for(p=new Tob(r);p.a<p.c.c.length;){n=Wv(Rob(p),9);n.k=h;for(w=new Tob(n.f);w.a<w.c.c.length;){u=Wv(Rob(w),7);for(f=new Tob(u.b);f.a<f.c.c.length;){c=Wv(Rob(f),12);if(c.c.f==n){continue}C=Wv(rJ(c,(Rib(),Eib)),24).a;this.a[h]+=C>0?C+1:1}for(e=new Tob(u.e);e.a<e.c.c.length;){c=Wv(Rob(e),12);if(c.d.f==n){continue}C=Wv(rJ(c,(Rib(),Eib)),24).a;this.c[h]+=C>0?C+1:1}}this.c[h]==0?QI(this.d,n):this.a[h]==0&&QI(this.e,n);++h}m=-1;l=1;j=new GU;D=Wv(rJ(a,(Rib(),Gib)),154);while(J>0){while(this.d.b!=0){G=Wv(YI(this.d),9);this.b[G.k]=m--;f8(this,G);--J}while(this.e.b!=0){H=Wv(YI(this.e),9);this.b[H.k]=l++;f8(this,H);--J}if(J>0){k=eyb;for(q=new Tob(r);q.a<q.c.c.length;){n=Wv(Rob(q),9);if(this.b[n.k]==0){s=this.c[n.k]-this.a[n.k];if(s>=k){if(s>k){j.c=xv(UF,syb,1,0,4,1);k=s}j.c[j.c.length]=n}}}i=Wv(yU(j,vvb(D,j.c.length)),9);this.b[i.k]=l++;f8(this,i);--J}}F=r.c.length+1;for(h=0;h<r.c.length;h++){this.b[h]<0&&(this.b[h]+=F)}for(o=new Tob(r);o.a<o.c.c.length;){n=Wv(Rob(o),9);B=Wv(FU(n.f,xv(BB,mAb,7,n.f.c.length,0,1)),346);for(v=0,A=B.length;v<A;++v){u=B[v];t=Wv(FU(u.e,xv(dB,gAb,12,u.e.c.length,0,1)),47);for(d=0,g=t.length;d<g;++d){c=t[d];I=c.d.f.k;if(this.b[n.k]>this.b[I]){cW(c,true);sJ(a,cib,(xkb(),xkb(),wkb))}}}}this.a=null;this.c=null;this.b=null;_I(this.e);_I(this.d);pI(b)};var d8;var XD=Nkb(AAb,'GreedyCycleBreaker',539);hI(540,1,BAb,m8);_.qc=function n8(a){return j8};_.sc=function o8(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;nI(b,'Interactive cycle breaking',1);k=new GU;for(m=new Tob(a.b);m.a<m.c.c.length;){l=Wv(Rob(m),9);l.k=1;n=kX(l).a;for(j=oX(l,(djb(),bjb)).mb();j.G();){i=Wv(j.H(),7);for(e=new Tob(i.e);e.a<e.c.c.length;){c=Wv(Rob(e),12);o=c.d.f;if(o!=l){p=kX(o).a;p<n&&(k.c[k.c.length]=c,true)}}}}for(f=new Tob(k);f.a<f.c.c.length;){c=Wv(Rob(f),12);cW(c,true)}k.c=xv(UF,syb,1,0,4,1);for(h=new Tob(a.b);h.a<h.c.c.length;){g=Wv(Rob(h),9);g.k>0&&l8(this,g,k)}for(d=new Tob(k);d.a<d.c.c.length;){c=Wv(Rob(d),12);cW(c,true)}k.c=xv(UF,syb,1,0,4,1);pI(b)};var j8;var YD=Nkb(AAb,'InteractiveCycleBreaker',540);hI(543,1,BAb,q8);_.qc=function r8(a){return TQ(RQ(new WQ,(d0(),z_)),I_)};_.sc=function s8(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p;nI(b,'Interactive node layering',1);c=new GU;for(l=new Tob(a.b);l.a<l.c.c.length;){j=Wv(Rob(l),9);h=j.i.a;g=h+j.j.a;g=h+1>g?h+1:g;p=new Fnb(c,0);d=null;while(p.b<p.d.Y()){n=(Bxb(p.b<p.d.Y()),Wv(p.d.sb(p.c=p.b++),239));if(n.c>=g){Bxb(p.b>0);p.a.sb(p.c=--p.b);break}else if(n.a>h){if(!d){vU(n.b,j);n.c=Qlb(n.c,h);n.a=Nlb(n.a,g);d=n}else{xU(d.b,n.b);d.a=Nlb(d.a,n.a);vnb(p)}}}if(!d){d=new t8;d.c=h;d.a=g;Anb(p,d);vU(d.b,j)}}f=a.c;i=0;for(o=new Tob(c);o.a<o.c.c.length;){n=Wv(Rob(o),239);e=new sY(a);e.k=i++;f.c[f.c.length]=e;for(m=new Tob(n.b);m.a<m.c.c.length;){j=Wv(Rob(m),9);rX(j,e);j.k=0}}for(k=new Tob(a.b);k.a<k.c.c.length;){j=Wv(Rob(k),9);j.k==0&&p8(this,j,a)}while((Cxb(0,f.c.length),Wv(f.c[0],16)).a.c.length==0){Cxb(0,f.c.length);f.c.splice(0,1)}a.b.c=xv(UF,syb,1,0,4,1);pI(b)};var $D=Nkb(CAb,'InteractiveLayerer',543);hI(239,1,{239:1},t8);_.a=0;_.c=0;var ZD=Nkb(CAb,'InteractiveLayerer/LayerSpan',239);hI(173,17,{180:1,173:1,3:1,23:1,17:1},y8);_.rc=function z8(){switch(this.e){case 0:return new U8;case 1:return new J8;case 2:return new q8;default:throw new slb('No implementation is available for the layerer '+(this.d!=null?this.d:''+this.e));}};var u8,v8,w8;var _D=Okb(CAb,'LayeringStrategy',173,IF,A8);var B8;hI(542,1,BAb,J8);_.qc=function K8(a){var b;b=XQ(D8);Ckb(Ixb(Xv(rJ(a,(Mjb(),njb)))))||gw(rJ(a,Ljb))===gw((ckb(),_jb))?QQ(b,E8):gw(rJ(a,Ljb))===gw((ckb(),akb))&&QQ(b,F8);Ckb(Ixb(Xv(rJ(a,Ijb))))&&UQ(b,(d0(),Y_));return b};_.sc=function L8(a,b){var c,d,e,f,g;nI(b,'Longest path layering',1);this.a=a;g=this.a.b;this.b=xv(mw,Yyb,26,g.c.length,12,1);c=0;for(f=new Tob(g);f.a<f.c.c.length;){d=Wv(Rob(f),9);d.k=c;this.b[c]=-1;++c}for(e=new Tob(g);e.a<e.c.c.length;){d=Wv(Rob(e),9);I8(this,d)}g.c=xv(UF,syb,1,0,4,1);this.a=null;this.b=null;pI(b)};var D8,E8,F8;var aE=Nkb(CAb,'LongestPathLayerer',542);hI(541,1,BAb,U8);_.qc=function V8(a){var b;b=XQ(M8);if(Ckb(Ixb(Xv(rJ(a,(Mjb(),njb)))))||gw(rJ(a,Ljb))===gw((ckb(),_jb))){QQ(b,N8);this.d=(ckb(),_jb)}else if(gw(rJ(a,Ljb))===gw((ckb(),akb))){QQ(b,O8);this.d=akb}return b};_.sc=function W8(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Network simplex layering',1);this.b=a;l=Wv(rJ(a,(Mjb(),Kjb)),24).a*4;k=this.b.b;if(k.c.length<1){pI(b);return}for(d=WI(Q8(this,k),0);d.b!=d.d.c;){c=Wv(_ub(d),20);f=l*hw(Tlb(c.Y()));e=T8(c);F7(S7(U7(T7(W7(e),f),this.b),this.d==(ckb(),_jb)),rI(b,1));h=this.b.c;for(j=new Tob(e.a);j.a<j.c.c.length;){i=Wv(Rob(j),61);while(h.c.length<=i.e){uU(h,h.c.length,new sY(this.b))}g=Wv(i.f,9);rX(g,Wv(yU(h,i.e),16))}}k.c=xv(UF,syb,1,0,4,1);this.a=null;this.b=null;this.c=null;pI(b)};var M8,N8,O8;var bE=Nkb(CAb,'NetworkSimplexLayerer',541);hI(326,1,{});var dE=Nkb(EAb,'AbstractPortDistributor',326);hI(558,1,fyb,a9);_.$b=function b9(a,b){return _8(this,Wv(a,7),Wv(b,7))};var cE=Nkb(EAb,'AbstractPortDistributor/1',558);hI(564,1,{},j9);var gE=Nkb(EAb,'BarycenterHeuristic',564);hI(272,1,{272:1},k9);_.b=0;_.d=0;_.e=false;var eE=Nkb(EAb,'BarycenterHeuristic/BarycenterState',272);hI(565,1,fyb,l9);_.$b=function m9(a,b){return f9(this.a,a,b)};var fE=Nkb(EAb,'BarycenterHeuristic/lambda$0$Type',565);hI(192,17,{180:1,192:1,3:1,23:1,17:1},q9);_.rc=function r9(){switch(this.e){case 0:return new I9;case 1:return new y9;default:throw new slb('No implementation is available for the crossing minimizer '+(this.d!=null?this.d:''+this.e));}};var n9,o9;var hE=Okb(EAb,'CrossingMinimizationStrategy',192,IF,s9);var t9;hI(526,1,BAb,y9);_.qc=function z9(a){var b;b=XQ(v9);Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),khb))&&TQ(b,(d0(),V_));return b};_.sc=function A9(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;nI(b,'Interactive crossing minimization',1);m=0;for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);c=0;j=0;for(i=new Tob(d.a);i.a<i.c.c.length;){g=Wv(Rob(i),9);if(g.i.a>0){c+=g.i.a+g.j.a/2;++j}for(l=new Tob(g.f);l.a<l.c.c.length;){k=Wv(Rob(l),7);k.k=m++}}c/=j;o=xv(kw,hyb,26,d.a.c.length,12,1);f=0;for(h=new Tob(d.a);h.a<h.c.c.length;){g=Wv(Rob(h),9);g.k=f++;o[g.k]=x9(g,c);g.g==(CX(),zX)&&sJ(g,(Rib(),wib),o[g.k])}Gpb(d.a,new C9(o))}n=new P9(xv(lw,tAb,26,m,12,1));Z8(n,jW(a));pI(b)};var v9;var jE=Nkb(EAb,'InteractiveCrossingMinimizer',526);hI(527,1,fyb,C9);_.$b=function D9(a,b){return B9(this,Wv(a,9),Wv(b,9))};var iE=Nkb(EAb,'InteractiveCrossingMinimizer/1',527);hI(525,1,BAb,I9);_.qc=function K9(a){var b;b=XQ(E9);Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),khb))&&TQ(b,(d0(),V_));return b};_.sc=function L9(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H;nI(b,'Layer sweep crossing minimization',1);F=Wv(rJ(a,(Rib(),Gib)),154);q=a.c.c.length;if(q<2){pI(b);return}G9(this,a);d=$xb;H=Wv(rJ(a,(Mjb(),Kjb)),24).a;c=xv(eE,Txb,671,a.c.c.length,0,2);m=0;for(p=new Tob(a.c);p.a<p.c.c.length;){o=Wv(Rob(p),16);o.k=m;c[m]=xv(eE,{671:1,3:1,5:1,6:1},272,o.a.c.length,0,1);n=0;for(v=new Tob(o.a);v.a<v.c.c.length;){u=Wv(Rob(v),9);u.k=n;c[m][n]=new k9(u);++n}++m}e=new X9(c,this.g);f=new j9(c,e,F,this.j);A=new P9(this.j);t=new M9(this.j);for(G=0;G<H&&d>0;G++){k=wvb(F,1)!=0;j=k?0:q-1;i=this.b[j];C=wvb(F,1)!=0?A:t;H9(i,f,k,false,true);g=$xb;h=true;do{J9(this.b,this.k);D=g;g=0;g+=bab(this.f,i,j);if(k){for(r=1;r<q;r++){l=this.b[r];X8(C,i,(djb(),bjb));H9(l,f,true,!h,false);g+=bab(this.f,l,r);this.d[r]||this.c[r-1]?(g+=lab(this.e,i,l)):(g+=hab(this.i,i,l));i=l}j=q-1}else{for(r=q-2;r>=0;r--){l=this.b[r];X8(C,i,(djb(),ajb));H9(l,f,false,!h,false);g+=bab(this.f,l,r);this.c[r]||this.d[r+1]?(g+=lab(this.e,l,i)):(g+=hab(this.i,l,i));i=l}j=0}h=false;k=!k}while(g<D&&g>0);if(g<d||D<d){if(g<=D){J9(this.b,this.a);d=g}else{J9(this.k,this.a);d=D}}}s=new Fnb(a.c,0);while(s.b<s.d.Y()){o=(Bxb(s.b<s.d.Y()),Wv(s.d.sb(s.c=s.b++),16));B=this.a[s.b-1];w=new Fnb(o.a,0);while(w.b<w.d.Y()){Bxb(w.b<w.d.Y());w.d.sb(w.c=w.b++);Enb(w,B[w.b-1])}}this.j=null;this.a=null;this.b=null;this.k=null;this.i=null;this.e=null;this.c=null;this.d=null;Pm(this.g);pI(b)};var E9;var kE=Nkb(EAb,'LayerSweepCrossingMinimizer',525);hI(327,326,{},M9);_.Hc=function N9(a,b,c){var d,e,f,g,h,i,j,k,l,m,n,o;m=this.a;if(LM(Wv(rJ(a,(eM(),TL)),28))){switch(c.e){case 1:{e=0;h=0;for(l=new Tob(a.f);l.a<l.c.c.length;){j=Wv(Rob(l),7);if(j.b.c.length!=0){++e;j.g==(sN(),$M)&&++h}}i=b+h;o=b+e;for(k=oX(a,(djb(),ajb)).mb();k.G();){j=Wv(k.H(),7);if(j.g==(sN(),$M)){m[j.k]=i;--i}else{m[j.k]=o;--o}}return e}case 2:{n=0;for(k=oX(a,(djb(),bjb)).mb();k.G();){j=Wv(k.H(),7);++n;m[j.k]=b+n}return n}default:throw new rlb;}}else{g=4;f=0;for(l=oX(a,c).mb();l.G();){j=Wv(l.H(),7);d=O9(c,j.g);g=g<d-1?g:d-1;f=f>d?f:d}if(f>g){for(k=oX(a,c).mb();k.G();){j=Wv(k.H(),7);m[j.k]=b+O9(c,j.g)-g}return f-g}return 0}};var lE=Nkb(EAb,'LayerTotalPortDistributor',327);hI(274,326,{},P9);_.Hc=function Q9(a,b,c){var d,e,f,g,h,i,j,k,l,m,n;l=this.a;if(LM(Wv(rJ(a,(eM(),TL)),28))){switch(c.e){case 1:{e=0;f=0;for(k=new Tob(a.f);k.a<k.c.c.length;){i=Wv(Rob(k),7);if(i.b.c.length!=0){++e;i.g==(sN(),$M)&&++f}}d=1/(e+1);g=b+f*d;n=b+1-d;for(j=oX(a,(djb(),ajb)).mb();j.G();){i=Wv(j.H(),7);if(i.g==(sN(),$M)){l[i.k]=g;g-=d}else{l[i.k]=n;n-=d}}break}case 2:{h=0;for(k=new Tob(a.f);k.a<k.c.c.length;){i=Wv(Rob(k),7);i.e.c.length==0||++h}d=1/(h+1);m=b+d;for(j=oX(a,(djb(),bjb)).mb();j.G();){i=Wv(j.H(),7);l[i.k]=m;m+=d}break}default:throw new slb(GAb);}}else{for(j=oX(a,c).mb();j.G();){i=Wv(j.H(),7);l[i.k]=b+R9(c,i.g)}}return 1};var mE=Nkb(EAb,'NodeRelativePortDistributor',274);hI(566,1,{},X9);var oE=Nkb(KAb,'ForsterConstraintResolver',566);hI(102,1,{102:1},$9,_9);_.w=function aab(){var a,b;b=new zmb;b.a+='[';for(a=0;a<this.d.length;a++){ymb(b,tX(this.d[a]));W9(this.g,this.d[0]).a!=null&&ymb(ymb((b.a+='<',b),ilb(Ixb(W9(this.g,this.d[0]).a))),'>');a<this.d.length-1&&(b.a+=', ',b)}return b.a+=']',b.a};_.a=0;_.c=0;_.f=0;var nE=Nkb(KAb,'ForsterConstraintResolver/ConstraintGroup',102);hI(331,1,{});var pE=Nkb(LAb,'AbstractCrossingsCounter',331);hI(568,331,{},iab);var qE=Nkb(LAb,'BarthJuengerMutzelCrossingsCounter',568);hI(567,331,{},mab);var uE=Nkb(LAb,'HyperedgeCrossingsCounter',567);hI(197,1,{197:1,23:1},oab);_.F=function pab(a){return nab(this,Wv(a,197))};_.b=0;_.c=0;_.e=0;_.f=0;var tE=Nkb(LAb,'HyperedgeCrossingsCounter/Hyperedge',197);hI(156,1,{156:1,23:1},rab);_.F=function sab(a){return qab(this,Wv(a,156))};_.b=0;_.c=0;var sE=Nkb(LAb,'HyperedgeCrossingsCounter/HyperedgeCorner',156);hI(242,17,{242:1,3:1,23:1,17:1},wab);var tab,uab;var rE=Okb(LAb,'HyperedgeCrossingsCounter/HyperedgeCorner/Type',242,IF,xab);hI(545,1,BAb,Bab);_.qc=function Cab(a){return Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))?yab:null};_.sc=function Dab(a,b){var c,d;nI(b,'Interactive node placement',1);this.a=Wv(rJ(a,(Rib(),Kib)),134);for(d=new Tob(a.c);d.a<d.c.c.length;){c=Wv(Rob(d),16);Aab(this,c)}pI(b)};var yab;var vE=Nkb(MAb,'InteractiveNodePlacer',545);hI(546,1,BAb,Qab);_.qc=function Rab(a){return Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))?Eab:null};_.sc=function Sab(a,b){nI(b,'Linear segments node placement',1);this.b=Wv(rJ(a,(Rib(),Kib)),134);Pab(this,a);Lab(this,a);Iab(this,a);Oab(this);this.a=null;this.b=null;pI(b)};var Eab,Fab,Gab;var xE=Nkb(MAb,'LinearSegmentsNodePlacer',546);hI(111,1,{111:1,23:1},Wab);_.F=function Xab(a){return Tab(this,Wv(a,111))};_.t=function Yab(a){var b;if(aw(a,111)){b=Wv(a,111);return this.b==b.b}return false};_.v=function Zab(){return this.b};_.w=function $ab(){return 'ls'+Ze(this.f)};_.a=0;_.b=0;_.c=-1;_.d=-1;_.i=0;var wE=Nkb(MAb,'LinearSegmentsNodePlacer/LinearSegment',111);hI(548,1,BAb,cbb);_.qc=function dbb(a){return Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))?_ab:null};_.sc=function ebb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J;H=Wv(rJ(a,(Rib(),Kib)),134);u=(mp(),new ntb);t=0;e=new l7;for(i=new Tob(a.c);i.a<i.c.c.length;){g=Wv(Rob(i),16);D=null;C=null;for(n=new Tob(g.a);n.a<n.c.c.length;){m=Wv(Rob(n),9);++t;s=x7(new A7,e);s.f=m;Ltb(u.d,m,s);m.e.d=Llb(m.e.d);if(C){r=new d7;r.f=0;r.a=hw(Mlb(D.e.d+D.j.b+D.e.a+Xjb(H,Wv(C.f,9),m)));r.c=C;r.d=s;o7(C.g,r);o7(s.c,r)}D=m;C=s}}for(j=new Tob(a.c);j.a<j.c.c.length;){g=Wv(Rob(j),16);for(n=new Tob(g.a);n.a<n.c.c.length;){m=Wv(Rob(n),9);for(A=new Tob(m.f);A.a<A.c.c.length;){w=Wv(Rob(A),7);J=w.i.b+w.a.b;if(J!=Math.floor(J)){v=J-ZH(TH(Math.round(J)));w.i.b-=v}}}}for(h=new Tob(a.c);h.a<h.c.c.length;){g=Wv(Rob(h),16);for(n=new Tob(g.a);n.a<n.c.c.length;){m=Wv(Rob(n),9);for(l=Uh(mX(m));Cm(l);){k=Wv(Dm(l),12);if(bW(k)){continue}if(k.d.f.d==g){continue}G=k.c.f.e.d+k.c.i.b+k.c.a.b;I=k.d.f.e.d+k.d.i.b+k.d.a.b;c=I-G;B=hw(c);d=x7(new A7,e);o=new d7;o.f=bbb(k);o.a=B>0?B:0;o.c=d;o.d=Wv(Smb(u,k.c.f),61);o7(o.c.g,o);o7(o.d.c,o);F=new d7;F.f=bbb(k);F.a=B<0?-B:0;F.c=d;F.d=Wv(Smb(u,k.d.f),61);o7(F.c.g,F);o7(F.d.c,F)}}}f=Wv(rJ(a,(Mjb(),Kjb)),24).a*hw(Math.sqrt(t));F7(S7(T7(W7(e),f),false),rI(b,1));for(q=new Tob(e.a);q.a<q.c.c.length;){p=Wv(Rob(q),61);if(p.f!=null){m=Wv(p.f,9);m.i.b=p.e+m.e.d}}};var _ab;var yE=Nkb(MAb,'NetworkSimplexPlacer',548);hI(141,17,{180:1,141:1,3:1,23:1,17:1},lbb);_.rc=function mbb(){switch(this.e){case 0:return new sbb;case 1:return new Bab;case 2:return new Qab;case 3:return new dcb;case 4:return new cbb;default:throw new slb('No implementation is available for the node placer '+(this.d!=null?this.d:''+this.e));}};var fbb,gbb,hbb,ibb,jbb;var zE=Okb(MAb,'NodePlacementStrategy',141,IF,nbb);var obb;hI(544,1,BAb,sbb);_.qc=function tbb(a){return Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))?qbb:null};_.sc=function ubb(a,b){var c,d,e,f,g,h,i,j,k,l;nI(b,'Simple node placement',1);l=Wv(rJ(a,(Rib(),Kib)),134);h=0;for(f=new Tob(a.c);f.a<f.c.c.length;){d=Wv(Rob(f),16);g=d.c;g.b=0;c=null;for(j=new Tob(d.a);j.a<j.c.c.length;){i=Wv(Rob(j),9);!!c&&(g.b+=Vjb(l,i.g,c.g)*l.d);g.b+=i.e.d+i.j.b+i.e.a;c=i}h=Nlb(h,g.b)}for(e=new Tob(a.c);e.a<e.c.c.length;){d=Wv(Rob(e),16);g=d.c;k=(h-g.b)/2;c=null;for(j=new Tob(d.a);j.a<j.c.c.length;){i=Wv(Rob(j),9);!!c&&(k+=Vjb(l,i.g,c.g)*l.d);k+=i.e.d;i.i.b=k;k+=i.j.b+i.e.a;c=i}}pI(b)};var qbb;var AE=Nkb(MAb,'SimpleNodePlacer',544);hI(81,1,{81:1},Cbb);_.w=function Dbb(){var a;a='';this.c==(Gbb(),Fbb)?(a+=pzb):this.c==Ebb&&(a+=ozb);this.k==(Lbb(),Jbb)?(a+='DOWN'):this.k==Kbb?(a+='UP'):(a+='BALANCED');return a};var DE=Nkb(OAb,'BKAlignedLayout',81);hI(248,17,{248:1,3:1,23:1,17:1},Hbb);var Ebb,Fbb;var BE=Okb(OAb,'BKAlignedLayout/HDirection',248,IF,Ibb);hI(247,17,{247:1,3:1,23:1,17:1},Mbb);var Jbb,Kbb;var CE=Okb(OAb,'BKAlignedLayout/VDirection',247,IF,Nbb);hI(596,1,{},Qbb);var EE=Nkb(OAb,'BKAligner',596);hI(599,1,{},Vbb);var HE=Nkb(OAb,'BKCompactor',599);hI(279,1,{279:1},Wbb);_.a=0;var FE=Nkb(OAb,'BKCompactor/ClassEdge',279);hI(200,1,{200:1},Ybb);_.a=0;_.b=0;var GE=Nkb(OAb,'BKCompactor/ClassNode',200);hI(547,1,BAb,dcb);_.qc=function hcb(a){return Wv(rJ(a,(Rib(),jib)),18).kb((ohb(),hhb))?Zbb:null};_.sc=function icb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t;nI(b,'Brandes & Koepf node placement',1);this.b=a;this.d=scb(a);this.a=Ckb(Ixb(Xv(rJ(a,(Mjb(),mjb)))));this.e=gw(rJ(a,sjb))===gw((_gb(),Vgb));ccb(this,a);n=(Mh(4,Vyb),new HU(4));switch(Wv(rJ(a,sjb),124).e){case 3:o=new Cbb(a,this.d.d,(Lbb(),Jbb),(Gbb(),Ebb));n.c[n.c.length]=o;break;case 1:p=new Cbb(a,this.d.d,(Lbb(),Kbb),(Gbb(),Ebb));n.c[n.c.length]=p;break;case 4:s=new Cbb(a,this.d.d,(Lbb(),Jbb),(Gbb(),Fbb));n.c[n.c.length]=s;break;case 2:t=new Cbb(a,this.d.d,(Lbb(),Kbb),(Gbb(),Fbb));n.c[n.c.length]=t;break;default:o=new Cbb(a,this.d.d,(Lbb(),Jbb),(Gbb(),Ebb));p=new Cbb(a,this.d.d,Kbb,Ebb);s=new Cbb(a,this.d.d,Jbb,Fbb);t=new Cbb(a,this.d.d,Kbb,Fbb);n.c[n.c.length]=s;n.c[n.c.length]=t;n.c[n.c.length]=o;n.c[n.c.length]=p;}c=new Qbb(a,this.d);for(f=new Tob(n);f.a<f.c.c.length;){d=Wv(Rob(f),81);Pbb(c,d,this.c);Obb(d)}k=new Vbb(a,this.d);for(g=new Tob(n);g.a<g.c.c.length;){d=Wv(Rob(g),81);Sbb(k,d)}if(this.a){for(h=new Tob(n);h.a<h.c.c.length;){d=Wv(Rob(h),81);Fmb();d+' size is '+Abb(d)}}j=null;if(this.e){i=acb(this,n,this.d.d);_bb(this,a,i)&&(j=i)}if(!j){for(h=new Tob(n);h.a<h.c.c.length;){d=Wv(Rob(h),81);_bb(this,a,d)&&(!j||Abb(j)>Abb(d))&&(j=d)}}!j&&(j=(Cxb(0,n.c.length),Wv(n.c[0],81)));for(m=new Tob(a.c);m.a<m.c.c.length;){l=Wv(Rob(m),16);for(r=new Tob(l.a);r.a<r.c.c.length;){q=Wv(Rob(r),9);q.i.b=Ixb(j.n[q.k])+Ixb(j.d[q.k])}}if(this.a){Fmb();'Blocks: '+ecb(j);'Classes: '+fcb(j)}for(e=new Tob(n);e.a<e.c.c.length;){d=Wv(Rob(e),81);d.f=null;d.b=null;d.a=null;d.d=null;d.i=null;d.g=null;d.n=null}qcb(this.d);this.c.a.Q();pI(b)};_.a=false;_.e=false;var Zbb;var IE=Nkb(OAb,'BKNodePlacer',547);hI(194,17,{194:1,3:1,23:1,17:1},mcb);var jcb,kcb;var JE=Okb(OAb,'CompactionStrategy',194,IF,ncb);var ocb;hI(597,1,{},rcb);_.d=0;var LE=Nkb(OAb,'NeighborhoodInformation',597);hI(598,1,fyb,wcb);_.$b=function xcb(a,b){return vcb(this,Wv(a,27),Wv(b,27))};var KE=Nkb(OAb,'NeighborhoodInformation/NeighborComparator',598);hI(334,1,{});var PE=Nkb(OAb,'ThresholdStrategy',334);hI(602,334,{},Ccb);_.Ic=function Dcb(a,b,c){return this.a.k==(Lbb(),Kbb)?Uzb:Vzb};_.Jc=function Ecb(){};var ME=Nkb(OAb,'ThresholdStrategy/NullThresholdStrategy',602);hI(249,1,{249:1},Fcb);_.c=false;_.d=false;var NE=Nkb(OAb,'ThresholdStrategy/Postprocessable',249);hI(603,334,{},Jcb);_.Ic=function Kcb(a,b,c){var d,e,f;e=b==c;d=this.a.a[c.k]==b;if(!(e||d)){return a}f=a;if(this.a.c==(Gbb(),Fbb)){e&&(f=Gcb(this,b,true));(f==Infinity||f==-Infinity)&&d&&(f=Gcb(this,c,false))}else{e&&(f=Gcb(this,b,true));(f==Infinity||f==-Infinity)&&d&&(f=Gcb(this,c,false))}return f};_.Jc=function Lcb(){var a,b,c,d;while(this.d.b!=0){d=Wv(XI(this.d),249);c=Hcb(this,d);if(!c.a){continue}a=c.a;if(this.c.a[a.c.f.d.k]===this.c.a[a.d.f.d.k]){continue}b=Icb(this,d);b||Tvb(this.e,d)}while(this.e.a.c.length!=0){Icb(this,Wv(Svb(this.e),249))}};var OE=Nkb(OAb,'ThresholdStrategy/SimpleThresholdStrategy',603);hI(423,1,{180:1},Mcb);_.rc=function Ncb(){switch(this.a.e){case 1:return new Rdb;case 3:return new Wfb;default:return new Ycb;}};var QE=Nkb(PAb,'EdgeRouterFactory',423);hI(538,1,BAb,Ycb);_.qc=function Zcb(a){var b,c;c=Wv(rJ(a,(Rib(),jib)),18);b=new WQ;if(c.kb((ohb(),ihb))){QQ(b,Scb);QQ(b,Ucb)}if(c.kb(khb)||Ckb(Ixb(Xv(rJ(a,(Mjb(),rjb)))))){QQ(b,Ucb);c.kb(lhb)&&QQ(b,Vcb)}c.kb(hhb)&&QQ(b,Rcb);c.kb(nhb)&&QQ(b,Wcb);c.kb(jhb)&&QQ(b,Tcb);c.kb(ehb)&&QQ(b,Pcb);c.kb(ghb)&&QQ(b,Qcb);return b};_.sc=function $cb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o;nI(b,'Orthogonal edge routing',1);m=Wv(rJ(a,(Rib(),Kib)),134);Ckb(Ixb(Xv(rJ(a,(eM(),rL)))));k=new cdb(0,m.a);o=0;f=new Fnb(a.c,0);g=null;h=null;do{i=f.b<f.d.Y()?(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),16)):null;j=!i?null:i.a;if(g){UW(g,o);o+=g.c.a}n=!g?o:o+m.b;l=bdb(k,a,h,j,n);d=!g||nl(h,(Ndb(),Mdb));e=!i||nl(j,(Ndb(),Mdb));if(l>0){c=m.b+(l-1)*m.a;!!i&&(c+=m.b);c<m.f&&!d&&!e&&(c=m.f);o+=c}else !d&&!e&&(o+=m.f);g=i;h=j}while(i);a.e.a=o;pI(b)};var Pcb,Qcb,Rcb,Scb,Tcb,Ucb,Vcb,Wcb;var RE=Nkb(PAb,'OrthogonalEdgeRouter',538);hI(277,1,{},cdb);_.a=0;_.c=0;var XE=Nkb(PAb,'OrthogonalRoutingGenerator',277);hI(118,1,{118:1},kdb);_.w=function ldb(){return this.a+'->'+this.b};_.c=0;var SE=Nkb(PAb,'OrthogonalRoutingGenerator/Dependency',118);hI(80,1,{80:1,23:1},odb);_.F=function pdb(a){return ndb(this,Wv(a,80))};_.t=function qdb(a){var b;if(aw(a,80)){b=Wv(a,80);return this.d==b.d}return false};_.v=function rdb(){return this.d};_.w=function sdb(){var a,b,c,d;a=new Bmb('{');d=new Tob(this.g);while(d.a<d.c.c.length){c=Wv(Rob(d),7);b=lX(c.f);b==null&&(b='n'+jX(c.f));a.a+=''+b;d.a<d.c.c.length&&(a.a+=',',a)}a.a+='}';return a.a};_.a=NaN;_.c=0;_.d=0;_.f=0;_.i=0;_.k=NaN;var TE=Nkb(PAb,'OrthogonalRoutingGenerator/HyperNode',80);hI(580,1,{},tdb);_.Kc=function udb(a,b){var c,d,e,f,g,h,i,j,k,l;l=b+a.i*this.a.c;for(h=new Tob(a.g);h.a<h.c.c.length;){g=Wv(Rob(h),7);i=MI(Bv(tv(qz,1),Fzb,10,0,[g.f.i,g.i,g.a])).a;for(d=new Tob(g.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);j=c.d;k=MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).a;if((i-k<=0?0-(i-k):i-k)>dAb){e=new HI(i,l);QI(c.a,e);_cb(this.a,c,a,e,false);f=new HI(k,l);QI(c.a,f);_cb(this.a,c,a,f,false)}}}};_.Lc=function vdb(a){return a.f.i.a+a.i.a+a.a.a};_.Mc=function wdb(){return sN(),pN};_.Nc=function xdb(){return sN(),$M};var UE=Nkb(PAb,'OrthogonalRoutingGenerator/NorthToSouthRoutingStrategy',580);hI(581,1,{},ydb);_.Kc=function zdb(a,b){var c,d,e,f,g,h,i,j,k,l;l=b-a.i*this.a.c;for(h=new Tob(a.g);h.a<h.c.c.length;){g=Wv(Rob(h),7);i=MI(Bv(tv(qz,1),Fzb,10,0,[g.f.i,g.i,g.a])).a;for(d=new Tob(g.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);j=c.d;k=MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).a;if((i-k<=0?0-(i-k):i-k)>dAb){e=new HI(i,l);QI(c.a,e);_cb(this.a,c,a,e,false);f=new HI(k,l);QI(c.a,f);_cb(this.a,c,a,f,false)}}}};_.Lc=function Adb(a){return a.f.i.a+a.i.a+a.a.a};_.Mc=function Bdb(){return sN(),$M};_.Nc=function Cdb(){return sN(),pN};var VE=Nkb(PAb,'OrthogonalRoutingGenerator/SouthToNorthRoutingStrategy',581);hI(579,1,{},Ddb);_.Kc=function Edb(a,b){var c,d,e,f,g,h,i,j,k,l;l=b+a.i*this.a.c;for(h=new Tob(a.g);h.a<h.c.c.length;){g=Wv(Rob(h),7);i=MI(Bv(tv(qz,1),Fzb,10,0,[g.f.i,g.i,g.a])).b;for(d=new Tob(g.e);d.a<d.c.c.length;){c=Wv(Rob(d),12);j=c.d;k=MI(Bv(tv(qz,1),Fzb,10,0,[j.f.i,j.i,j.a])).b;if((i-k<=0?0-(i-k):i-k)>dAb){e=new HI(l,i);QI(c.a,e);_cb(this.a,c,a,e,true);f=new HI(l,k);QI(c.a,f);_cb(this.a,c,a,f,true)}}}};_.Lc=function Fdb(a){return a.f.i.b+a.i.b+a.a.b};_.Mc=function Gdb(){return sN(),ZM};_.Nc=function Hdb(){return sN(),rN};var WE=Nkb(PAb,'OrthogonalRoutingGenerator/WestToEastRoutingStrategy',579);hI(535,1,BAb,Rdb);_.qc=function Sdb(a){var b,c;c=Wv(rJ(a,(Rib(),jib)),18);b=new WQ;if(c.kb((ohb(),khb))||Ckb(Ixb(Xv(rJ(a,(Mjb(),rjb)))))){QQ(b,Kdb);c.kb(lhb)&&QQ(b,Ldb)}c.kb(ehb)&&QQ(b,Idb);c.kb(ghb)&&QQ(b,Jdb);return b};_.sc=function Tdb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v;nI(b,'Polyline edge routing',1);l=Wv(rJ(a,(Rib(),Jib)),15).a;c=Wv(rJ(a,(Mjb(),qjb)),15).a;q=0;if(a.c.c.length!=0){r=Pdb(Wv(yU(a.c,0),16));q=0.4*c*r}f=new Fnb(a.c,0);while(f.b<f.d.Y()){e=(Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),16));d=nl(e,Mdb);d&&q>0&&(q-=l);UW(e,q);i=0;for(k=new Tob(e.a);k.a<k.c.c.length;){j=Wv(Rob(k),9);h=0;for(n=Uh(mX(j));Cm(n);){m=Wv(Dm(n),12);o=MX(m.c).b;p=MX(m.d).b;if(e==m.d.f.d){s=m.c;t=m.d;u=(MI(Bv(tv(qz,1),Fzb,10,0,[s.f.i,s.i,s.a])).b+MI(Bv(tv(qz,1),Fzb,10,0,[t.f.i,t.i,t.a])).b)/2;s.g==(sN(),ZM)?(v=new HI(q+s.f.d.c.a+0.4*c*(o-p<=0?0-(o-p):o-p),u)):(v=new HI(q-0.4*c*(o-p<=0?0-(o-p):o-p),u));rn(m.a,0,v);if(m.c.g==rN){o=0;p=0}}h=h>(p-o<=0?0-(p-o):p-o)?h:p-o<=0?0-(p-o):p-o}switch(j.g.e){case 0:case 4:case 1:case 3:Qdb(this,j,q);}i=i>h?i:h}if(f.b<f.d.Y()){r=Pdb((Bxb(f.b<f.d.Y()),Wv(f.d.sb(f.c=f.b++),16)));i=i>r?i:r;Bxb(f.b>0);f.a.sb(f.c=--f.b)}g=0.4*c*i;!d&&f.b<f.d.Y()&&(g+=l);q+=e.c.a+g}this.a.a.Q();a.e.a=q;pI(b)};var Idb,Jdb,Kdb,Ldb,Mdb;var ZE=Nkb(PAb,'PolylineEdgeRouter',535);hI(536,1,_zb,Vdb);_.D=function Wdb(a){return Udb(Wv(a,9))};var YE=Nkb(PAb,'PolylineEdgeRouter/1',536);hI(75,1,{75:1},deb);_.w=function eeb(){var a,b,c,d;c=new zmb;!!this.e&&ymb(ymb(c,zc(this.e)),': ');for(b=WI(Zdb(this),0);b.b!=b.d.c;){a=Wv(_ub(b),7);ymb(ymb(umb(ymb(c,(d=OX(a),d==null?'p_'+a.k:'p_'+d)),32),zc(a.g)),' / ')}return kkb(c,pmb(c.a)-2-1)};_.j=0;_.k=0;var $E=Nkb(QAb,'ConnectedSelfLoopComponent',75);hI(60,17,{60:1,3:1,23:1,17:1},Peb);_.c=0;var feb,geb,heb,ieb,jeb,keb,leb,meb,neb,oeb,peb,qeb,reb,seb,teb,ueb,veb,web,xeb,yeb,zeb,Aeb,Beb,Ceb,Deb,Eeb,Feb,Geb,Heb;var _E=Okb(QAb,'LoopSide',60,IF,Seb);hI(203,1,{},dfb,efb,ffb);_.w=function pfb(){return this.b.w()};_.c=0;_.d=false;_.e=false;_.f=false;_.i=0;_.j=0;var bF=Nkb(QAb,'NubSpline',203);hI(92,1,{92:1},sfb,tfb);var aF=Nkb(QAb,'NubSpline/PolarCP',92);hI(281,203,{},ufb);var cF=Nkb(QAb,'NubsSelfLoop',281);hI(112,1,{},Bfb,Cfb,Dfb,Efb,Ffb);_.a=jzb;_.b=rAb;_.c=jzb;_.d=rAb;var dF=Nkb(QAb,'Rectangle',112);hI(537,1,BAb,Wfb);_.qc=function Yfb(a){var b,c;b=new WQ;c=Wv(rJ(a,(Rib(),jib)),18);c.kb((ohb(),nhb))&&QQ(b,Lfb);c.kb(ehb)&&QQ(b,Hfb);if(c.kb(khb)||Ckb(Ixb(Xv(rJ(a,(Mjb(),rjb)))))){QQ(b,Jfb);c.kb(lhb)&&QQ(b,Kfb)}c.kb(ghb)&&QQ(b,Ifb);return b};_.sc=function $fb(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,A,B,C,D,F,G,H,I,J,K,L;nI(b,'Spline edge routing',1);u=Wv(rJ(a,(Rib(),Jib)),15).a;this.a=u*Wv(rJ(a,(Mjb(),qjb)),15).a;L=0;q=new Tob(a.c);r=null;J=(mp(),new ntb);I=new GU;i=true;j=true;do{A=q.a<q.c.c.length?Wv(Rob(q),16):null;m=new GU;g=new GU;s=new Wub;C=new Wub;G=new Wub;Tfb(new RJ(r,A),new RJ(s,C),g,J,I,G);Sfb(s,C,(fgb(),dgb),true,g,m);Sfb(s,C,dgb,false,g,m);Sfb(s,C,egb,true,g,m);Sfb(s,C,egb,false,g,m);Rfb(g,s,C,m);H=new Fnb(m,0);while(H.b<H.d.Y()){k=(Bxb(H.b<H.d.Y()),Wv(H.d.sb(H.c=H.b++),77));K=new Fnb(m,H.b);while(K.b<K.d.Y()){l=(Bxb(K.b<K.d.Y()),Wv(K.d.sb(K.c=K.b++),77));Qfb(k,l)}}Xfb(m,Wv(rJ(a,Gib),154));_fb(m);B=L+10;if(A){j=!A||nl(A.a,(Ndb(),Mdb));t=-1;for(e=new Tob(m);e.a<e.c.c.length;){c=Wv(Rob(e),77);t=Plb(t,c.n)}++t;if(t>0){n=(t+1)*this.a;n<u&&!i&&!j&&(n=u);B+=n}else i||j||Vfb(r)||Vfb(A)||(B+=u);UW(A,B)}for(F=(w=(new Snb(G.a)).a.bb().mb(),new Ynb(w));F.a.G();){D=(h=Wv(F.a.H(),21),Wv(h.yb(),12));v=D.c.f.i;hJ(D.a,v);for(p=new Tob(D.b);p.a<p.c.c.length;){o=Wv(Rob(p),33);vI(o.i,v)}}for(f=new Tob(m);f.a<f.c.c.length;){c=Wv(Rob(f),77);c.f?Ofb(c,L):Pfb(this,c,L,B)}if(A){L=B+A.c.a+10}else{t=-1;for(e=new Tob(m);e.a<e.c.c.length;){c=Wv(Rob(e),77);t=Plb(t,c.n)}t>=0&&(L+=(t+2)*this.a)}r=A;i=j}while(A);for(d=new Tob(I);d.a<d.c.c.length;){c=Wv(Rob(d),12);Nfb(c,J)}a.e.a=L;pI(b)};_.a=3;var Hfb,Ifb,Jfb,Kfb,Lfb;var hF=Nkb(QAb,'SplineEdgeRouter',537);hI(117,1,{117:1},bgb);_.w=function cgb(){return this.a+' ->('+this.c+') '+this.b};_.c=0;var eF=Nkb(QAb,'SplineEdgeRouter/Dependency',117);hI(223,17,{223:1,3:1,23:1,17:1},ggb);var dgb,egb;var fF=Okb(QAb,'SplineEdgeRouter/SideToProcess',223,IF,hgb);hI(77,1,{77:1,23:1},lgb,mgb);_.F=function ngb(a){return jgb(this,Wv(a,77))};_.a=0;_.b=0;_.e=0;_.f=false;_.i=0;_.k=0;_.n=0;_.p=0;var gF=Nkb(QAb,'SplineEdgeRouter/SplineHyperEdge',77);hI(123,17,{123:1,3:1,23:1,17:1},Agb);var tgb,ugb,vgb,wgb,xgb,ygb;var iF=Okb(VAb,'ContentAlignment',123,IF,Bgb);var Cgb;hI(218,17,{218:1,3:1,23:1,17:1},Igb);var Egb,Fgb,Ggb;var jF=Okb(VAb,'EdgeConstraint',218,IF,Jgb);hI(115,17,{115:1,3:1,23:1,17:1},Rgb);var Kgb,Lgb,Mgb,Ngb,Ogb;var kF=Okb(VAb,'EdgeLabelSideSelection',115,IF,Sgb);var Tgb;hI(124,17,{124:1,3:1,23:1,17:1},ahb);var Vgb,Wgb,Xgb,Ygb,Zgb,$gb;var lF=Okb(VAb,'FixedAlignment',124,IF,bhb);var chb;hI(113,17,{113:1,3:1,23:1,17:1},phb);var ehb,fhb,ghb,hhb,ihb,jhb,khb,lhb,mhb,nhb;var mF=Okb(VAb,'GraphProperties',113,IF,qhb);hI(110,17,{110:1,3:1,23:1,17:1},Ahb);_.a=false;_.b=false;_.c=false;var rhb,shb,thb,uhb,vhb,whb,xhb,yhb;var nF=Okb(VAb,'GreedySwitchType',110,IF,Bhb);var Chb;hI(140,17,{140:1,3:1,23:1,17:1},Ihb);var Ehb,Fhb,Ghb;var oF=Okb(VAb,'InLayerConstraint',140,IF,Jhb);hI(174,17,{174:1,3:1,23:1,17:1},Nhb);var Khb,Lhb;var pF=Okb(VAb,'InteractiveReferencePoint',174,IF,Ohb);var Phb;var Rhb,Shb,Thb,Uhb,Vhb,Whb,Xhb,Yhb,Zhb,$hb,_hb,aib,bib,cib,dib,eib,fib,gib,hib,iib,jib,kib,lib,mib,nib,oib,pib,qib,rib,sib,tib,uib,vib,wib,xib,yib,zib,Aib,Bib,Cib,Dib,Eib,Fib,Gib,Hib,Iib,Jib,Kib,Lib,Mib,Nib,Oib,Pib,Qib;hI(85,17,{85:1,3:1,23:1,17:1},Yib);var Sib,Tib,Uib,Vib,Wib;var qF=Okb(VAb,'LayerConstraint',85,IF,Zib);var $ib;hI(219,17,{219:1,3:1,23:1,17:1},ejb);var ajb,bjb,cjb;var rF=Okb(VAb,'PortType',219,IF,fjb);var gjb,hjb,ijb,jjb,kjb,ljb,mjb,njb,ojb,pjb,qjb,rjb,sjb,tjb,ujb,vjb,wjb,xjb,yjb,zjb,Ajb,Bjb,Cjb,Djb,Ejb,Fjb,Gjb,Hjb,Ijb,Jjb,Kjb,Ljb;hI(153,17,{153:1,3:1,23:1,17:1},Rjb);var Njb,Ojb,Pjb;var sF=Okb(VAb,'SelfLoopPlacement',153,IF,Sjb);var Tjb;hI(134,1,{134:1},$jb);_.a=0;_.b=0;_.c=0;_.d=0;_.e=0;_.f=0;var tF=Nkb(VAb,'Spacings',134);hI(172,17,{172:1,3:1,23:1,17:1},dkb);var _jb,akb,bkb;var uF=Okb(VAb,'WideNodesStrategy',172,IF,ekb);var fkb;hI(644,1,{});var xF=Nkb(nyb,'OutputStream',644);hI(645,644,{});var vF=Nkb(nyb,'FilterOutputStream',645);hI(291,645,{},hkb);var yF=Nkb(nyb,'PrintStream',291);hI(255,1,{});_.w=function mkb(){return this.a};var AF=Nkb(kyb,'AbstractStringBuilder',255);hI(621,95,Vxb,pkb);var BF=Nkb(kyb,'ArrayIndexOutOfBoundsException',621);hI(290,72,Vxb,qkb,rkb);var CF=Nkb(kyb,'ArrayStoreException',290);hI(252,46,Uxb);var JF=Nkb(kyb,'Error',252);hI(84,252,Uxb,tkb,ukb);var DF=Nkb(kyb,'AssertionError',84);Sv={3:1,349:1,23:1};var vkb,wkb;var EF=Nkb(kyb,'Boolean',349);Tv={3:1,23:1,184:1,231:1};var HF=Nkb(kyb,'Double',184);hI(15,231,{3:1,23:1,15:1,231:1},klb,llb);_.F=function mlb(a){return jlb(this,Wv(a,15))};_.t=function nlb(a){return aw(a,15)&&Wv(a,15).a==this.a};_.v=function olb(){return hw(this.a)};_.w=function plb(){return qlb(this.a)};_.a=0;var LF=Nkb(kyb,'Float',15);hI(101,72,Vxb,tlb,ulb);var NF=Nkb(kyb,'IllegalStateException',101);var Flb;var Hlb;hI(608,72,Vxb,Ulb);var QF=Nkb(kyb,'NegativeArraySizeException',608);hI(76,72,{3:1,54:1,76:1,46:1},Vlb,Wlb);var RF=Nkb(kyb,'NullPointerException',76);hI(130,29,{3:1,54:1,29:1,130:1,46:1},Xlb,Ylb);var SF=Nkb(kyb,'NumberFormatException',130);hI(146,1,{3:1,146:1},Zlb);_.t=function $lb(a){var b;if(aw(a,146)){b=Wv(a,146);return this.c==b.c&&ovb(this.d,b.d)&&ovb(this.a,b.a)&&ovb(this.b,b.b)}return false};_.v=function _lb(){return fpb(Bv(tv(UF,1),syb,1,4,[Elb(this.c),this.a,this.d,this.b]))};_.w=function amb(){return this.a+'.'+this.d+'('+(this.b!=null?this.b:'Unknown Source')+(this.c>=0?':'+this.c:'')+')'};_.c=0;var WF=Nkb(kyb,'StackTraceElement',146);hI(98,255,{345:1},zmb,Amb,Bmb);var YF=Nkb(kyb,'StringBuilder',98);var Dmb,Emb;hI(45,72,{3:1,54:1,46:1,45:1},Hmb,Imb);var aG=Nkb(kyb,'UnsupportedOperationException',45);hI(213,638,Byb);_.Q=function _mb(){Ymb(this)};_.R=function anb(a){return Qmb(this,a)};_.ab=function bnb(a){return Rmb(this,a,this.e)||Rmb(this,a,this.d)};_.bb=function cnb(){return new inb(this)};_.cb=function dnb(a){return Smb(this,a)};_.db=function enb(a,b){return Umb(this,a,b)};_.eb=function fnb(a){return Wmb(this,a)};_.Y=function gnb(){return Zmb(this)};var hG=Nkb(Cyb,'AbstractHashMap',213);hI(120,641,Eyb,inb);_.Q=function jnb(){this.a.Q()};_.kb=function knb(a){return hnb(this,a)};_.mb=function lnb(){return new rnb(this.a)};_.nb=function mnb(a){var b;if(hnb(this,a)){b=Wv(a,21).yb();this.a.eb(b);return true}return false};_.Y=function nnb(){return this.a.Y()};var gG=Nkb(Cyb,'AbstractHashMap/EntrySet',120);hI(148,1,Ayb,rnb);_.H=function tnb(){return pnb(this)};_.G=function snb(){return this.b};_.I=function unb(){qnb(this)};_.b=false;var fG=Nkb(Cyb,'AbstractHashMap/EntrySetIterator',148);hI(162,1,Ayb,wnb);_.G=function xnb(){return this.b<this.d.Y()};_.H=function ynb(){return Bxb(this.G()),this.d.sb(this.c=this.b++)};_.I=function znb(){vnb(this)};_.b=0;_.c=-1;var iG=Nkb(Cyb,'AbstractList/IteratorImpl',162);hI(43,162,Hyb,Fnb);_.J=function Gnb(a){Anb(this,a)};_.K=function Hnb(){return this.b>0};_.L=function Inb(){return this.b};_.M=function Jnb(){return Dnb(this)};_.N=function Knb(){return this.b-1};_.O=function Lnb(a){Enb(this,a)};var jG=Nkb(Cyb,'AbstractList/ListIteratorImpl',43);hI(258,647,Fyb,Mnb);_.rb=function Nnb(a,b){Fxb(a,this.b);this.c.rb(this.a+a,b);++this.b};_.sb=function Onb(a){Cxb(a,this.b);return this.c.sb(this.a+a)};_.vb=function Pnb(a){var b;Cxb(a,this.b);b=this.c.vb(this.a+a);--this.b;return b};_.wb=function Qnb(a,b){Cxb(a,this.b);return this.c.wb(this.a+a,b)};_.Y=function Rnb(){return this.b};_.a=0;_.b=0;var kG=Nkb(Cyb,'AbstractList/SubList',258);hI(36,641,Eyb,Snb);_.Q=function Tnb(){this.a.Q()};_.kb=function Unb(a){return this.a.R(a)};_.mb=function Vnb(){var a;return a=this.a.bb().mb(),new Ynb(a)};_.nb=function Wnb(a){if(this.a.R(a)){this.a.eb(a);return true}return false};_.Y=function Xnb(){return this.a.Y()};var nG=Nkb(Cyb,'AbstractMap/1',36);hI(40,1,Ayb,Ynb);_.G=function Znb(){return this.a.G()};_.H=function $nb(){var a;return a=Wv(this.a.H(),21),a.yb()};_.I=function _nb(){this.a.I()};var mG=Nkb(Cyb,'AbstractMap/1/1',40);hI(211,640,Dyb,aob);_.Q=function bob(){this.a.Q()};_.kb=function cob(a){return this.a.ab(a)};_.mb=function dob(){var a;return a=this.a.bb().mb(),new fob(a)};_.Y=function eob(){return this.a.Y()};var pG=Nkb(Cyb,'AbstractMap/2',211);hI(212,1,Ayb,fob);_.G=function gob(){return this.a.G()};_.H=function hob(){var a;return a=Wv(this.a.H(),21),a.zb()};_.I=function iob(){this.a.I()};var oG=Nkb(Cyb,'AbstractMap/2/1',212);hI(210,1,{210:1,21:1});_.t=function kob(a){var b;if(!aw(a,21)){return false}b=Wv(a,21);return ovb(this.d,b.yb())&&ovb(this.e,b.zb())};_.yb=function lob(){return this.d};_.zb=function mob(){return this.e};_.v=function nob(){return pvb(this.d)^pvb(this.e)};_.Ab=function oob(a){return job(this,a)};_.w=function pob(){return this.d+'='+this.e};var qG=Nkb(Cyb,'AbstractMap/AbstractEntry',210);hI(163,210,{210:1,163:1,21:1},qob);var rG=Nkb(Cyb,'AbstractMap/SimpleEntry',163);hI(652,1,Jyb);_.t=function rob(a){var b;if(!aw(a,21)){return false}b=Wv(a,21);return ovb(this.yb(),b.yb())&&ovb(this.zb(),b.zb())};_.v=function sob(){return pvb(this.yb())^pvb(this.zb())};_.w=function tob(){return this.yb()+'='+this.zb()};var sG=Nkb(Cyb,Kyb,652);hI(639,638,Byb);_._=function wob(a){return uob(this,a)};_.R=function xob(a){return vob(this,a)};_.bb=function yob(){return new Bob(this)};_.cb=function zob(a){return re(Wvb(this,a))};_.W=function Aob(){return new Gob(this)};var xG=Nkb(Cyb,'AbstractNavigableMap',639);hI(287,641,Eyb,Bob);_.kb=function Cob(a){return aw(a,21)&&uob(this.b,Wv(a,21))};_.mb=function Dob(){return new rwb(this.b)};_.nb=function Eob(a){var b;if(aw(a,21)){b=Wv(a,21);return dwb(this.b,b)}return false};_.Y=function Fob(){return this.b.c};var uG=Nkb(Cyb,'AbstractNavigableMap/EntrySet',287);hI(229,641,Iyb,Gob);_.Q=function Hob(){Vvb(this.a)};_.kb=function Iob(a){return vob(this.a,a)};_.mb=function Job(){var a;return a=new rwb((new wwb(this.a)).b),new Mob(a)};_.nb=function Kob(a){if(vob(this.a,a)){cwb(this.a,a);return true}return false};_.Y=function Lob(){return this.a.c};var wG=Nkb(Cyb,'AbstractNavigableMap/NavigableKeySet',229);hI(230,1,Ayb,Mob);_.G=function Nob(){return Bnb(this.a.a)};_.H=function Oob(){var a;return a=pwb(this.a),a.yb()};_.I=function Pob(){qwb(this.a)};var vG=Nkb(Cyb,'AbstractNavigableMap/NavigableKeySet/1',230);hI(4,1,Ayb,Tob);_.G=function Uob(){return Qob(this)};_.H=function Vob(){return Rob(this)};_.I=function Wob(){Sob(this)};_.a=0;_.b=-1;var AG=Nkb(Cyb,'ArrayList/1',4);hI(94,647,XAb,opb);_.kb=function ppb(a){return dn(this,a)!=-1};_.sb=function qpb(a){return mpb(this,a)};_.wb=function rpb(a,b){var c;c=(Cxb(a,this.a.length),this.a[a]);Av(this.a,a,b);return c};_.Y=function spb(){return this.a.length};_.ob=function tpb(){return npb(this,xv(UF,syb,1,this.a.length,4,1))};_.pb=function upb(a){return npb(this,a)};var CG=Nkb(Cyb,'Arrays/ArrayList',94);var vpb,wpb,xpb;hI(413,1,fyb,Ipb);_.$b=function Jpb(a,b){return zT(b,a)};var DG=Nkb(Cyb,'Collections/2',413);hI(406,647,XAb,Kpb);_.kb=function Lpb(a){return false};_.sb=function Mpb(a){Cxb(a,0);return null};_.mb=function Npb(){return ypb(),Rpb(),Qpb};_.tb=function Opb(){return ypb(),Rpb(),Qpb};_.Y=function Ppb(){return 0};var FG=Nkb(Cyb,'Collections/EmptyList',406);hI(407,1,Hyb,Spb);_.J=function Tpb(a){throw new Hmb};_.G=function Upb(){return false};_.K=function Vpb(){return false};_.H=function Wpb(){throw new nvb};_.L=function Xpb(){return 0};_.M=function Ypb(){throw new nvb};_.N=function Zpb(){return -1};_.I=function $pb(){throw new tlb};_.O=function _pb(a){throw new tlb};var Qpb;var EG=Nkb(Cyb,'Collections/EmptyListIterator',407);hI(409,638,Ryb,aqb);_.R=function bqb(a){return false};_.ab=function cqb(a){return false};_.bb=function dqb(){return ypb(),xpb};_.cb=function eqb(a){return null};_.W=function fqb(){return ypb(),xpb};_.Y=function gqb(){return 0};_.fb=function hqb(){return ypb(),vpb};var GG=Nkb(Cyb,'Collections/EmptyMap',409);hI(408,641,Syb,iqb);_.kb=function jqb(a){return false};_.mb=function kqb(){return ypb(),Rpb(),Qpb};_.Y=function lqb(){return 0};var HG=Nkb(Cyb,'Collections/EmptySet',408);hI(410,1,fyb,pqb);_.$b=function qqb(a,b){return oqb(Wv(a,23),Wv(b,23))};var mqb;var IG=Nkb(Cyb,'Collections/ReverseComparator',410);hI(411,647,{3:1,22:1,19:1,20:1},rqb);_.kb=function sqb(a){return ovb(this.a,a)};_.sb=function tqb(a){Cxb(a,1);return this.a};_.Y=function uqb(){return 1};var JG=Nkb(Cyb,'Collections/SingletonList',411);hI(217,1,Dyb,zqb);_.ib=function Aqb(a){return vqb()};_.jb=function Bqb(a){return wqb()};_.Q=function Cqb(){xqb()};_.kb=function Dqb(a){return this.b.kb(a)};_.lb=function Eqb(a){return this.b.lb(a)};_.V=function Fqb(){return this.b.V()};_.mb=function Gqb(){return new Nqb(this.b.mb())};_.nb=function Hqb(a){return yqb()};_.Y=function Iqb(){return this.b.Y()};_.ob=function Jqb(){return this.b.ob()};_.pb=function Kqb(a){return this.b.pb(a)};_.w=function Lqb(){return xb(this.b)};var LG=Nkb(Cyb,'Collections/UnmodifiableCollection',217);hI(152,1,Ayb,Nqb);_.G=function Oqb(){return this.b.G()};_.H=function Pqb(){return this.b.H()};_.I=function Qqb(){Mqb()};var KG=Nkb(Cyb,'Collections/UnmodifiableCollectionIterator',152);hI(233,217,Fyb,Rqb);_.rb=function Sqb(a,b){throw new Hmb};_.t=function Tqb(a){return this.a.t(a)};_.sb=function Uqb(a){return this.a.sb(a)};_.v=function Vqb(){return this.a.v()};_.V=function Wqb(){return this.a.V()};_.tb=function Xqb(){return new arb(this.a.ub(0))};_.ub=function Yqb(a){return new arb(this.a.ub(a))};_.vb=function Zqb(a){throw new Hmb};_.wb=function $qb(a,b){throw new Hmb};_.xb=function _qb(a,b){return new Rqb(this.a.xb(a,b))};var NG=Nkb(Cyb,'Collections/UnmodifiableList',233);hI(309,152,Hyb,arb);_.J=function brb(a){throw new Hmb};_.K=function crb(){return this.a.K()};_.L=function drb(){return this.a.L()};_.M=function erb(){return this.a.M()};_.N=function frb(){return this.a.N()};_.O=function grb(a){throw new Hmb};var MG=Nkb(Cyb,'Collections/UnmodifiableListIterator',309);hI(305,1,Byb,mrb);_.Q=function nrb(){throw new Hmb};_.R=function orb(a){return this.c.R(a)};_.ab=function prb(a){return hrb(this,a)};_.bb=function qrb(){return irb(this)};_.t=function rrb(a){return jrb(this,a)};_.cb=function srb(a){return this.c.cb(a)};_.v=function trb(){return this.c.v()};_.V=function urb(){return this.c.V()};_.W=function vrb(){return krb(this)};_.db=function wrb(a,b){throw new Hmb};_.eb=function xrb(a){throw new Hmb};_.Y=function yrb(){return this.c.Y()};_.w=function zrb(){return xb(this.c)};_.fb=function Arb(){return lrb(this)};var RG=Nkb(Cyb,'Collections/UnmodifiableMap',305);hI(151,217,Eyb,Frb);_.t=function Grb(a){return Drb(this,a)};_.v=function Hrb(){return this.b.v()};var TG=Nkb(Cyb,'Collections/UnmodifiableSet',151);hI(412,151,Eyb,Nrb);_.kb=function Orb(a){return Irb(this,a)};_.lb=function Prb(a){return Jrb(this,a)};_.mb=function Qrb(){var a;return a=this.b.mb(),new Trb(a)};_.ob=function Rrb(){return Krb(this)};_.pb=function Srb(a){return Lrb(this,a)};var QG=Nkb(Cyb,'Collections/UnmodifiableMap/UnmodifiableEntrySet',412);hI(263,1,Ayb,Trb);_.H=function Vrb(){return new Xrb(Wv(this.a.H(),21))};_.G=function Urb(){return this.a.G()};_.I=function Wrb(){throw new Hmb};var OG=Nkb(Cyb,'Collections/UnmodifiableMap/UnmodifiableEntrySet/1',263);hI(306,1,Jyb,Xrb);_.t=function Yrb(a){return this.a.t(a)};_.yb=function Zrb(){return this.a.yb()};_.zb=function $rb(){return this.a.zb()};_.v=function _rb(){return this.a.v()};_.Ab=function asb(a){throw new Hmb};_.w=function bsb(){return xb(this.a)};var PG=Nkb(Cyb,'Collections/UnmodifiableMap/UnmodifiableEntrySet/UnmodifiableEntry',306);hI(307,233,Gyb,csb);var SG=Nkb(Cyb,'Collections/UnmodifiableRandomAccessList',307);hI(308,151,Iyb,dsb);_.t=function esb(a){return this.a.t(a)};_.v=function fsb(){return this.a.v()};var UG=Nkb(Cyb,'Collections/UnmodifiableSortedSet',308);var gsb;hI(522,1,fyb,isb);_.$b=function jsb(a,b){Dxb(a);Dxb(b);return Akb(Wv(a,23),b)};var VG=Nkb(Cyb,'Comparators/1',522);hI(202,72,Vxb,nsb);var WG=Nkb(Cyb,'ConcurrentModificationException',202);hI(609,72,Vxb,osb);var XG=Nkb(Cyb,'EmptyStackException',609);hI(319,638,Byb,vsb);_.db=function Bsb(a,b){return ssb(this,a,b)};_.Q=function wsb(){psb(this)};_.R=function xsb(a){return Ysb(this.a,a)};_.ab=function ysb(a){var b,c;for(c=new jtb(this.a);c.a<c.c.a.length;){b=itb(c);if(ovb(a,this.b[b.e])){return true}}return false};_.bb=function zsb(){return new Fsb(this)};_.cb=function Asb(a){return qsb(this,a)};_.eb=function Csb(a){return tsb(this,a)};_.Y=function Dsb(){return this.a.c};var _G=Nkb(Cyb,'EnumMap',319);hI(236,641,Eyb,Fsb);_.Q=function Gsb(){psb(this.a)};_.kb=function Hsb(a){return Esb(this,a)};_.mb=function Isb(){return new Lsb(this.a)};_.nb=function Jsb(a){var b;if(Esb(this,a)){b=Wv(a,21).yb();tsb(this.a,b);return true}return false};_.Y=function Ksb(){return this.a.a.c};var ZG=Nkb(Cyb,'EnumMap/EntrySet',236);hI(237,1,Ayb,Lsb);_.H=function Nsb(){return this.b=itb(this.a),new Psb(this.c,this.b)};_.G=function Msb(){return htb(this.a)};_.I=function Osb(){uxb(!!this.b);tsb(this.c,this.b);this.b=null};var YG=Nkb(Cyb,'EnumMap/EntrySetIterator',237);hI(238,652,Jyb,Psb);_.yb=function Qsb(){return this.a};_.zb=function Rsb(){return this.b.b[this.a.e]};_.Ab=function Ssb(a){return usb(this.b,this.a.e,a)};var $G=Nkb(Cyb,'EnumMap/MapEntry',238);hI(86,641,{22:1,19:1,86:1,18:1});var cH=Nkb(Cyb,'EnumSet',86);hI(66,86,{22:1,19:1,86:1,66:1,18:1},atb);_.ib=function btb(a){return Wsb(this,Wv(a,17))};_.kb=function ctb(a){return Ysb(this,a)};_.mb=function dtb(){return new jtb(this)};_.nb=function etb(a){return $sb(this,a)};_.Y=function ftb(){return this.c};_.c=0;var bH=Nkb(Cyb,'EnumSet/EnumSetImpl',66);hI(167,1,Ayb,jtb);_.H=function ltb(){return itb(this)};_.G=function ktb(){return htb(this)};_.I=function mtb(){uxb(this.b!=-1);Av(this.c.b,this.b,null);--this.c.c;this.b=-1};_.a=-1;_.b=-1;var aH=Nkb(Cyb,'EnumSet/EnumSetImpl/IteratorImpl',167);hI(30,213,YAb,ntb,otb,ptb);_.Uc=function qtb(a,b){return gw(a)===gw(b)||a!=null&&rb(a,b)};_.Vc=function rtb(a){var b;b=vb(a);return b|0};var dH=Nkb(Cyb,'HashMap',30);hI(50,641,ZAb,vtb,wtb,xtb);_.ib=function ztb(a){return stb(this,a)};_.Q=function Atb(){this.a.Q()};_.Wc=function Btb(){return new xtb(this)};_.kb=function Ctb(a){return ttb(this,a)};_.V=function Dtb(){return this.a.Y()==0};_.mb=function Etb(){var a;return a=(new Snb(this.a)).a.bb().mb(),new Ynb(a)};_.nb=function Ftb(a){return utb(this,a)};_.Y=function Gtb(){return this.a.Y()};_.w=function Htb(){return Ze(new Snb(this.a))};var eH=Nkb(Cyb,'HashSet',50);hI(418,1,Oyb,Ntb);_.mb=function Otb(){return new Ptb(this)};_.c=0;var gH=Nkb(Cyb,'InternalHashCodeMap',418);hI(312,1,Ayb,Ptb);_.H=function Rtb(){return this.d=this.a[this.c++],this.d};_.G=function Qtb(){var a;if(this.c<this.a.length){return true}a=this.b.next();if(!a.done){this.a=a.value[1];this.c=0;return true}return false};_.I=function Stb(){Mtb(this.e,this.d.yb());this.c!=0&&--this.c};_.c=0;_.d=null;var fH=Nkb(Cyb,'InternalHashCodeMap/1',312);var Xtb;hI(382,1,Oyb,fub);_.mb=function gub(){return new hub(this)};_.c=0;_.d=0;var jH=Nkb(Cyb,'InternalStringMap',382);hI(293,1,Ayb,hub);_.H=function jub(){return this.c=this.a,this.a=this.b.next(),new lub(this.d,this.c,this.d.d)};_.G=function iub(){return !this.a.done};_.I=function kub(){eub(this.d,this.c.value[0])};var hH=Nkb(Cyb,'InternalStringMap/1',293);hI(383,652,Jyb,lub);_.yb=function mub(){return this.b.value[0]};_.zb=function nub(){if(this.a.d!=this.c){return cub(this.a,this.b.value[0])}return this.b.value[1]};_.Ab=function oub(a){return dub(this.a,this.b.value[0],a)};_.c=0;var iH=Nkb(Cyb,'InternalStringMap/2',383);hI(155,30,YAb,wub,xub);_.Q=function yub(){qub(this)};_.R=function zub(a){return Qmb(this.c,a)};_.ab=function Aub(a){var b;b=this.b.a;while(b!=this.b){if(ovb(b.e,a)){return true}b=b.a}return false};_.bb=function Bub(){return new Lub(this)};_.cb=function Cub(a){return rub(this,a)};_.db=function Dub(a,b){return tub(this,a,b)};_.eb=function Eub(a){return vub(this,a)};_.Y=function Fub(){return Zmb(this.c)};_.a=false;var nH=Nkb(Cyb,'LinkedHashMap',155);hI(176,163,{210:1,163:1,176:1,21:1},Iub,Jub);var kH=Nkb(Cyb,'LinkedHashMap/ChainEntry',176);hI(270,641,Eyb,Lub);_.Q=function Mub(){qub(this.a)};_.kb=function Nub(a){return Kub(this,a)};_.mb=function Oub(){return new Sub(this)};_.nb=function Pub(a){var b;if(Kub(this,a)){b=Wv(a,21).yb();vub(this.a,b);return true}return false};_.Y=function Qub(){return Zmb(this.a.c)};var mH=Nkb(Cyb,'LinkedHashMap/EntrySet',270);hI(271,1,Ayb,Sub);_.H=function Uub(){return Rub(this)};_.G=function Tub(){return this.b!=this.c.a.b};_.I=function Vub(){uxb(!!this.a);ksb(this.c.a.c,this);Hub(this.a);Wmb(this.c.a.c,this.a.d);lsb(this.c.a.c,this);this.a=null};var lH=Nkb(Cyb,'LinkedHashMap/EntrySet/EntryIterator',271);hI(70,50,ZAb,Wub,Xub,Yub);_.Wc=function Zub(){return new Yub(this)};var oH=Nkb(Cyb,'LinkedHashSet',70);hI(372,1,Hyb,cvb);_.J=function dvb(a){$ub(this,a)};_.G=function evb(){return this.b!=this.d.c};_.K=function fvb(){return this.b.b!=this.d.a};_.H=function gvb(){return _ub(this)};_.L=function hvb(){return this.a};_.M=function ivb(){return avb(this)};_.N=function jvb(){return this.a-1};_.I=function kvb(){bvb(this)};_.O=function lvb(a){uxb(!!this.c);this.c.c=a};_.a=0;_.c=null;var pH=Nkb(Cyb,'LinkedList/ListIteratorImpl',372);hI(259,1,{},mvb);var qH=Nkb(Cyb,'LinkedList/Node',259);hI(74,72,{3:1,54:1,46:1,74:1},nvb);var tH=Nkb(Cyb,'NoSuchElementException',74);hI(154,1,{154:1},yvb,zvb);_.a=0;_.b=0;var qvb,rvb,svb=0;var uH=Nkb(Cyb,'Random',154);hI(607,647,cBb);_.rb=function Avb(a,b){Dvb(a,this.a.c.length+1);uU(this.a,a,b)};_.ib=function Bvb(a){return vU(this.a,a)};_.jb=function Cvb(a){return xU(this.a,a)};_.Q=function Evb(){this.a.c=xv(UF,syb,1,0,4,1)};_.kb=function Fvb(a){return zU(this.a,a,0)!=-1};_.lb=function Gvb(a){return Xe(this.a,a)};_.sb=function Hvb(a){Dvb(a,this.a.c.length);return yU(this.a,a)};_.V=function Ivb(){return this.a.c.length==0};_.mb=function Jvb(){return new Tob(this.a)};_.vb=function Kvb(a){return Dvb(a,this.a.c.length),AU(this.a,a)};_.Xb=function Lvb(a,b){CU(this.a,a,b)};_.wb=function Mvb(a,b){Dvb(a,this.a.c.length);return DU(this.a,a,b)};_.Y=function Nvb(){return this.a.c.length};_.xb=function Ovb(a,b){return new Mnb(this.a,a,b)};_.ob=function Pvb(){return EU(this.a)};_.pb=function Qvb(a){return FU(this.a,a)};_.w=function Rvb(){return Ze(this.a)};var GH=Nkb(Cyb,'Vector',607);hI(337,607,cBb,Uvb);var vH=Nkb(Cyb,'Stack',337);hI(253,639,Ryb,iwb,jwb);_.Q=function kwb(){Vvb(this)};_.bb=function lwb(){return new wwb(this)};_.db=function mwb(a,b){return bwb(this,a,b)};_.eb=function nwb(a){return cwb(this,a)};_.Y=function owb(){return this.c};_.c=0;var EH=Nkb(Cyb,'TreeMap',253);hI(182,1,Ayb,rwb);_.H=function uwb(){return pwb(this)};_.G=function twb(){return Bnb(this.a)};_.I=function vwb(){qwb(this)};var wH=Nkb(Cyb,'TreeMap/EntryIterator',182);hI(209,287,Eyb,wwb);_.Q=function xwb(){Vvb(this.a)};var xH=Nkb(Cyb,'TreeMap/EntrySet',209);hI(183,163,{210:1,163:1,21:1,183:1},ywb);_.b=false;var yH=Nkb(Cyb,'TreeMap/Node',183);hI(254,1,{},zwb);_.w=function Awb(){return 'State: mv='+this.c+' value='+this.d+' done='+this.a+' found='+this.b};_.a=false;_.b=false;_.c=false;var zH=Nkb(Cyb,'TreeMap/State',254);hI(138,17,dBb,Gwb);_.Xc=function Hwb(){return false};_.Yc=function Iwb(){return false};var Bwb,Cwb,Dwb,Ewb;var DH=Okb(Cyb,'TreeMap/SubMapType',138,IF,Jwb);hI(352,138,dBb,Kwb);_.Yc=function Lwb(){return true};var AH=Okb(Cyb,'TreeMap/SubMapType/1',352,DH,null);hI(353,138,dBb,Mwb);_.Xc=function Nwb(){return true};_.Yc=function Owb(){return true};var BH=Okb(Cyb,'TreeMap/SubMapType/2',353,DH,null);hI(354,138,dBb,Pwb);_.Xc=function Qwb(){return true};var CH=Okb(Cyb,'TreeMap/SubMapType/3',354,DH,null);hI(191,641,{3:1,22:1,19:1,18:1,137:1,191:1},Vwb,Wwb);_.ib=function Xwb(a){return Rwb(this,a)};_.Q=function Ywb(){Vvb(this.a)};_.kb=function Zwb(a){return vob(this.a,a)};_.mb=function $wb(){var a;return a=new rwb((new wwb((new Gob(this.a)).a)).b),new Mob(a)};_.nb=function _wb(a){return Uwb(this,a)};_.Y=function axb(){return this.a.c};var FH=Nkb(Cyb,'TreeSet',191);var sxb=0;var Kxb,Lxb=0,Mxb;var mw=Qkb('int','I');var KH=Qkb('boolean','Z');var jw=Qkb('char','C');var kw=Qkb('double','D');var lw=Qkb('float','F');var Rxb=zt;var gwtOnLoad=gwtOnLoad=dI;bI(lI);eI('permProps',[[['locale','default'],['user.agent','gecko1_8']]]);
var $moduleName, $moduleBase, $stats = function(){}, $sessionId = function(){};
gwtOnLoad(null,'klay',null);
})();


/***/ }),

/***/ 6874:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AttributeDefinitions = void 0;
const Attribute_1 = __webpack_require__(46);
/** @internal */
class AttributeDefinitions {
    constructor() {
        this.attributes = [];
        this.nameToAttribute = {};
    }
    addWithAll(name, modelName, defaultValue, alwaysWriteJson) {
        const attr = new Attribute_1.Attribute(name, modelName, defaultValue, alwaysWriteJson);
        this.attributes.push(attr);
        this.nameToAttribute[name] = attr;
        return attr;
    }
    addInherited(name, modelName) {
        return this.addWithAll(name, modelName, undefined, false);
    }
    add(name, defaultValue, alwaysWriteJson) {
        return this.addWithAll(name, undefined, defaultValue, alwaysWriteJson);
    }
    getAttributes() {
        return this.attributes;
    }
    getModelName(name) {
        const conversion = this.nameToAttribute[name];
        if (conversion !== undefined) {
            return conversion.modelName;
        }
        return undefined;
    }
    toJson(jsonObj, obj) {
        for (const attr of this.attributes) {
            const fromValue = obj[attr.name];
            if (attr.alwaysWriteJson || fromValue !== attr.defaultValue) {
                jsonObj[attr.name] = fromValue;
            }
        }
    }
    fromJson(jsonObj, obj) {
        for (const attr of this.attributes) {
            const fromValue = jsonObj[attr.name];
            if (fromValue === undefined) {
                obj[attr.name] = attr.defaultValue;
            }
            else {
                obj[attr.name] = fromValue;
            }
        }
    }
    update(jsonObj, obj) {
        for (const attr of this.attributes) {
            if (jsonObj.hasOwnProperty(attr.name)) {
                const fromValue = jsonObj[attr.name];
                if (fromValue === undefined) {
                    delete obj[attr.name];
                }
                else {
                    obj[attr.name] = fromValue;
                }
            }
        }
    }
    setDefaults(obj) {
        for (const attr of this.attributes) {
            obj[attr.name] = attr.defaultValue;
        }
    }
    toTypescriptInterface(name, parentAttributes) {
        const lines = [];
        const sorted = this.attributes.sort((a, b) => a.name.localeCompare(b.name));
        // const sorted = this.attributes;
        lines.push("export interface I" + name + "Attributes {");
        for (let i = 0; i < sorted.length; i++) {
            const c = sorted[i];
            let type = c.type;
            let defaultValue = undefined;
            let attr = c;
            let inherited = undefined;
            if (attr.defaultValue !== undefined) {
                defaultValue = attr.defaultValue;
            }
            else if (attr.modelName !== undefined
                && parentAttributes !== undefined
                && parentAttributes.nameToAttribute[attr.modelName] !== undefined) {
                inherited = attr.modelName;
                attr = parentAttributes.nameToAttribute[attr.modelName];
                defaultValue = attr.defaultValue;
                type = attr.type;
            }
            let defValue = JSON.stringify(defaultValue);
            const required = attr.required || attr.fixed ? "" : "?";
            if (c.fixed) {
                lines.push("\t" + c.name + ": " + defValue + ";");
            }
            else {
                const comment = (defaultValue !== undefined ? "default: " + defValue : "") +
                    (inherited !== undefined ? " - inherited from global " + inherited : "");
                lines.push("\t" + c.name + required + ": " + type + ";" +
                    (comment.length > 0 ? " // " + comment : ""));
            }
        }
        lines.push("}");
        return lines.join("\n");
    }
}
exports.AttributeDefinitions = AttributeDefinitions;
//# sourceMappingURL=AttributeDefinitions.js.map

/***/ }),

/***/ 7241:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6540);

/* harmony default export */ __webpack_exports__.A = (react__WEBPACK_IMPORTED_MODULE_0__.createContext(null));

/***/ }),

/***/ 7333:
/***/ (function() {

"use strict";
// extracted by mini-css-extract-plugin


/***/ }),

/***/ 7353:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Ay: function() { return /* binding */ esm_Transition; }
});

// UNUSED EXPORTS: ENTERED, ENTERING, EXITED, EXITING, UNMOUNTED

// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
var objectWithoutPropertiesLoose = __webpack_require__(8587);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js + 1 modules
var inheritsLoose = __webpack_require__(5540);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(6540);
// EXTERNAL MODULE: ./node_modules/react-dom/index.js
var react_dom = __webpack_require__(961);
;// ./node_modules/react-transition-group/esm/config.js
/* harmony default export */ var config = ({
  disabled: false
});
// EXTERNAL MODULE: ./node_modules/react-transition-group/esm/TransitionGroupContext.js
var TransitionGroupContext = __webpack_require__(7241);
;// ./node_modules/react-transition-group/esm/utils/reflow.js
var forceReflow = function forceReflow(node) {
  return node.scrollTop;
};
;// ./node_modules/react-transition-group/esm/Transition.js









var UNMOUNTED = 'unmounted';
var EXITED = 'exited';
var ENTERING = 'entering';
var ENTERED = 'entered';
var EXITING = 'exiting';
/**
 * The Transition component lets you describe a transition from one component
 * state to another _over time_ with a simple declarative API. Most commonly
 * it's used to animate the mounting and unmounting of a component, but can also
 * be used to describe in-place transition states as well.
 *
 * ---
 *
 * **Note**: `Transition` is a platform-agnostic base component. If you're using
 * transitions in CSS, you'll probably want to use
 * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)
 * instead. It inherits all the features of `Transition`, but contains
 * additional features necessary to play nice with CSS transitions (hence the
 * name of the component).
 *
 * ---
 *
 * By default the `Transition` component does not alter the behavior of the
 * component it renders, it only tracks "enter" and "exit" states for the
 * components. It's up to you to give meaning and effect to those states. For
 * example we can add styles to a component when it enters or exits:
 *
 * ```jsx
 * import { Transition } from 'react-transition-group';
 *
 * const duration = 300;
 *
 * const defaultStyle = {
 *   transition: `opacity ${duration}ms ease-in-out`,
 *   opacity: 0,
 * }
 *
 * const transitionStyles = {
 *   entering: { opacity: 1 },
 *   entered:  { opacity: 1 },
 *   exiting:  { opacity: 0 },
 *   exited:  { opacity: 0 },
 * };
 *
 * const Fade = ({ in: inProp }) => (
 *   <Transition in={inProp} timeout={duration}>
 *     {state => (
 *       <div style={{
 *         ...defaultStyle,
 *         ...transitionStyles[state]
 *       }}>
 *         I'm a fade Transition!
 *       </div>
 *     )}
 *   </Transition>
 * );
 * ```
 *
 * There are 4 main states a Transition can be in:
 *  - `'entering'`
 *  - `'entered'`
 *  - `'exiting'`
 *  - `'exited'`
 *
 * Transition state is toggled via the `in` prop. When `true` the component
 * begins the "Enter" stage. During this stage, the component will shift from
 * its current transition state, to `'entering'` for the duration of the
 * transition and then to the `'entered'` stage once it's complete. Let's take
 * the following example (we'll use the
 * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):
 *
 * ```jsx
 * function App() {
 *   const [inProp, setInProp] = useState(false);
 *   return (
 *     <div>
 *       <Transition in={inProp} timeout={500}>
 *         {state => (
 *           // ...
 *         )}
 *       </Transition>
 *       <button onClick={() => setInProp(true)}>
 *         Click to Enter
 *       </button>
 *     </div>
 *   );
 * }
 * ```
 *
 * When the button is clicked the component will shift to the `'entering'` state
 * and stay there for 500ms (the value of `timeout`) before it finally switches
 * to `'entered'`.
 *
 * When `in` is `false` the same thing happens except the state moves from
 * `'exiting'` to `'exited'`.
 */

var Transition = /*#__PURE__*/function (_React$Component) {
  (0,inheritsLoose/* default */.A)(Transition, _React$Component);

  function Transition(props, context) {
    var _this;

    _this = _React$Component.call(this, props, context) || this;
    var parentGroup = context; // In the context of a TransitionGroup all enters are really appears

    var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
    var initialStatus;
    _this.appearStatus = null;

    if (props.in) {
      if (appear) {
        initialStatus = EXITED;
        _this.appearStatus = ENTERING;
      } else {
        initialStatus = ENTERED;
      }
    } else {
      if (props.unmountOnExit || props.mountOnEnter) {
        initialStatus = UNMOUNTED;
      } else {
        initialStatus = EXITED;
      }
    }

    _this.state = {
      status: initialStatus
    };
    _this.nextCallback = null;
    return _this;
  }

  Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
    var nextIn = _ref.in;

    if (nextIn && prevState.status === UNMOUNTED) {
      return {
        status: EXITED
      };
    }

    return null;
  } // getSnapshotBeforeUpdate(prevProps) {
  //   let nextStatus = null
  //   if (prevProps !== this.props) {
  //     const { status } = this.state
  //     if (this.props.in) {
  //       if (status !== ENTERING && status !== ENTERED) {
  //         nextStatus = ENTERING
  //       }
  //     } else {
  //       if (status === ENTERING || status === ENTERED) {
  //         nextStatus = EXITING
  //       }
  //     }
  //   }
  //   return { nextStatus }
  // }
  ;

  var _proto = Transition.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.updateStatus(true, this.appearStatus);
  };

  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    var nextStatus = null;

    if (prevProps !== this.props) {
      var status = this.state.status;

      if (this.props.in) {
        if (status !== ENTERING && status !== ENTERED) {
          nextStatus = ENTERING;
        }
      } else {
        if (status === ENTERING || status === ENTERED) {
          nextStatus = EXITING;
        }
      }
    }

    this.updateStatus(false, nextStatus);
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    this.cancelNextCallback();
  };

  _proto.getTimeouts = function getTimeouts() {
    var timeout = this.props.timeout;
    var exit, enter, appear;
    exit = enter = appear = timeout;

    if (timeout != null && typeof timeout !== 'number') {
      exit = timeout.exit;
      enter = timeout.enter; // TODO: remove fallback for next major

      appear = timeout.appear !== undefined ? timeout.appear : enter;
    }

    return {
      exit: exit,
      enter: enter,
      appear: appear
    };
  };

  _proto.updateStatus = function updateStatus(mounting, nextStatus) {
    if (mounting === void 0) {
      mounting = false;
    }

    if (nextStatus !== null) {
      // nextStatus will always be ENTERING or EXITING.
      this.cancelNextCallback();

      if (nextStatus === ENTERING) {
        if (this.props.unmountOnExit || this.props.mountOnEnter) {
          var node = this.props.nodeRef ? this.props.nodeRef.current : react_dom.findDOMNode(this); // https://github.com/reactjs/react-transition-group/pull/749
          // With unmountOnExit or mountOnEnter, the enter animation should happen at the transition between `exited` and `entering`.
          // To make the animation happen,  we have to separate each rendering and avoid being processed as batched.

          if (node) forceReflow(node);
        }

        this.performEnter(mounting);
      } else {
        this.performExit();
      }
    } else if (this.props.unmountOnExit && this.state.status === EXITED) {
      this.setState({
        status: UNMOUNTED
      });
    }
  };

  _proto.performEnter = function performEnter(mounting) {
    var _this2 = this;

    var enter = this.props.enter;
    var appearing = this.context ? this.context.isMounting : mounting;

    var _ref2 = this.props.nodeRef ? [appearing] : [react_dom.findDOMNode(this), appearing],
        maybeNode = _ref2[0],
        maybeAppearing = _ref2[1];

    var timeouts = this.getTimeouts();
    var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
    // if we are mounting and running this it means appear _must_ be set

    if (!mounting && !enter || config.disabled) {
      this.safeSetState({
        status: ENTERED
      }, function () {
        _this2.props.onEntered(maybeNode);
      });
      return;
    }

    this.props.onEnter(maybeNode, maybeAppearing);
    this.safeSetState({
      status: ENTERING
    }, function () {
      _this2.props.onEntering(maybeNode, maybeAppearing);

      _this2.onTransitionEnd(enterTimeout, function () {
        _this2.safeSetState({
          status: ENTERED
        }, function () {
          _this2.props.onEntered(maybeNode, maybeAppearing);
        });
      });
    });
  };

  _proto.performExit = function performExit() {
    var _this3 = this;

    var exit = this.props.exit;
    var timeouts = this.getTimeouts();
    var maybeNode = this.props.nodeRef ? undefined : react_dom.findDOMNode(this); // no exit animation skip right to EXITED

    if (!exit || config.disabled) {
      this.safeSetState({
        status: EXITED
      }, function () {
        _this3.props.onExited(maybeNode);
      });
      return;
    }

    this.props.onExit(maybeNode);
    this.safeSetState({
      status: EXITING
    }, function () {
      _this3.props.onExiting(maybeNode);

      _this3.onTransitionEnd(timeouts.exit, function () {
        _this3.safeSetState({
          status: EXITED
        }, function () {
          _this3.props.onExited(maybeNode);
        });
      });
    });
  };

  _proto.cancelNextCallback = function cancelNextCallback() {
    if (this.nextCallback !== null) {
      this.nextCallback.cancel();
      this.nextCallback = null;
    }
  };

  _proto.safeSetState = function safeSetState(nextState, callback) {
    // This shouldn't be necessary, but there are weird race conditions with
    // setState callbacks and unmounting in testing, so always make sure that
    // we can cancel any pending setState callbacks after we unmount.
    callback = this.setNextCallback(callback);
    this.setState(nextState, callback);
  };

  _proto.setNextCallback = function setNextCallback(callback) {
    var _this4 = this;

    var active = true;

    this.nextCallback = function (event) {
      if (active) {
        active = false;
        _this4.nextCallback = null;
        callback(event);
      }
    };

    this.nextCallback.cancel = function () {
      active = false;
    };

    return this.nextCallback;
  };

  _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {
    this.setNextCallback(handler);
    var node = this.props.nodeRef ? this.props.nodeRef.current : react_dom.findDOMNode(this);
    var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;

    if (!node || doesNotHaveTimeoutOrListener) {
      setTimeout(this.nextCallback, 0);
      return;
    }

    if (this.props.addEndListener) {
      var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],
          maybeNode = _ref3[0],
          maybeNextCallback = _ref3[1];

      this.props.addEndListener(maybeNode, maybeNextCallback);
    }

    if (timeout != null) {
      setTimeout(this.nextCallback, timeout);
    }
  };

  _proto.render = function render() {
    var status = this.state.status;

    if (status === UNMOUNTED) {
      return null;
    }

    var _this$props = this.props,
        children = _this$props.children,
        _in = _this$props.in,
        _mountOnEnter = _this$props.mountOnEnter,
        _unmountOnExit = _this$props.unmountOnExit,
        _appear = _this$props.appear,
        _enter = _this$props.enter,
        _exit = _this$props.exit,
        _timeout = _this$props.timeout,
        _addEndListener = _this$props.addEndListener,
        _onEnter = _this$props.onEnter,
        _onEntering = _this$props.onEntering,
        _onEntered = _this$props.onEntered,
        _onExit = _this$props.onExit,
        _onExiting = _this$props.onExiting,
        _onExited = _this$props.onExited,
        _nodeRef = _this$props.nodeRef,
        childProps = (0,objectWithoutPropertiesLoose/* default */.A)(_this$props, ["children", "in", "mountOnEnter", "unmountOnExit", "appear", "enter", "exit", "timeout", "addEndListener", "onEnter", "onEntering", "onEntered", "onExit", "onExiting", "onExited", "nodeRef"]);

    return (
      /*#__PURE__*/
      // allows for nested Transitions
      react.createElement(TransitionGroupContext/* default */.A.Provider, {
        value: null
      }, typeof children === 'function' ? children(status, childProps) : react.cloneElement(react.Children.only(children), childProps))
    );
  };

  return Transition;
}(react.Component);

Transition.contextType = TransitionGroupContext/* default */.A;
Transition.propTypes =  false ? 0 : {}; // Name the function so it is clearer in the documentation

function noop() {}

Transition.defaultProps = {
  in: false,
  mountOnEnter: false,
  unmountOnExit: false,
  appear: false,
  enter: true,
  exit: true,
  onEnter: noop,
  onEntering: noop,
  onEntered: noop,
  onExit: noop,
  onExiting: noop,
  onExited: noop
};
Transition.UNMOUNTED = UNMOUNTED;
Transition.EXITED = EXITED;
Transition.ENTERING = ENTERING;
Transition.ENTERED = ENTERED;
Transition.EXITING = EXITING;
/* harmony default export */ var esm_Transition = (Transition);

/***/ }),

/***/ 7393:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Model = void 0;
const Attribute_1 = __webpack_require__(46);
const AttributeDefinitions_1 = __webpack_require__(6874);
const DockLocation_1 = __webpack_require__(8324);
const Orientation_1 = __webpack_require__(1648);
const Rect_1 = __webpack_require__(2530);
const Actions_1 = __webpack_require__(9103);
const BorderNode_1 = __webpack_require__(1480);
const BorderSet_1 = __webpack_require__(9026);
const RowNode_1 = __webpack_require__(4948);
const TabNode_1 = __webpack_require__(8171);
const TabSetNode_1 = __webpack_require__(9555);
const Utils_1 = __webpack_require__(2429);
/**
 * Class containing the Tree of Nodes used by the FlexLayout component
 */
class Model {
    /**
     * Loads the model from the given json object
     * @param json the json model to load
     * @returns {Model} a new Model object
     */
    static fromJson(json) {
        const model = new Model();
        Model._attributeDefinitions.fromJson(json.global, model._attributes);
        if (json.borders) {
            model._borders = BorderSet_1.BorderSet._fromJson(json.borders, model);
        }
        model._root = RowNode_1.RowNode._fromJson(json.layout, model);
        model._tidy(); // initial tidy of node tree
        return model;
    }
    /** @internal */
    static _createAttributeDefinitions() {
        const attributeDefinitions = new AttributeDefinitions_1.AttributeDefinitions();
        attributeDefinitions.add("legacyOverflowMenu", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("enableEdgeDock", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("rootOrientationVertical", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("marginInsets", { top: 0, right: 0, bottom: 0, left: 0 })
            .setType("IInsets");
        attributeDefinitions.add("enableUseVisibility", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("enableRotateBorderIcons", true).setType(Attribute_1.Attribute.BOOLEAN);
        // splitter
        attributeDefinitions.add("splitterSize", -1).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("splitterExtra", 0).setType(Attribute_1.Attribute.NUMBER);
        // tab
        attributeDefinitions.add("tabEnableClose", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabCloseType", 1).setType("ICloseType");
        attributeDefinitions.add("tabEnableFloat", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabEnableDrag", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabEnableRename", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabContentClassName", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("tabClassName", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("tabIcon", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("tabEnableRenderOnDemand", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabDragSpeed", 0.3).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("tabBorderWidth", -1).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("tabBorderHeight", -1).setType(Attribute_1.Attribute.NUMBER);
        // tabset
        attributeDefinitions.add("tabSetEnableDeleteWhenEmpty", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetEnableDrop", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetEnableDrag", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetEnableDivide", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetEnableMaximize", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetEnableClose", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetEnableSingleTabStretch", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetAutoSelectTab", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetClassNameTabStrip", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("tabSetClassNameHeader", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("tabSetEnableTabStrip", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabSetHeaderHeight", 0).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("tabSetTabStripHeight", 0).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("tabSetMarginInsets", { top: 0, right: 0, bottom: 0, left: 0 })
            .setType("IInsets");
        attributeDefinitions.add("tabSetBorderInsets", { top: 0, right: 0, bottom: 0, left: 0 })
            .setType("IInsets");
        attributeDefinitions.add("tabSetTabLocation", "top").setType("ITabLocation");
        attributeDefinitions.add("tabSetMinWidth", 0).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("tabSetMinHeight", 0).setType(Attribute_1.Attribute.NUMBER);
        // border
        attributeDefinitions.add("borderSize", 200).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("borderMinSize", 0).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("borderBarSize", 0).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("borderEnableDrop", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("borderAutoSelectTabWhenOpen", true).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("borderAutoSelectTabWhenClosed", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("borderClassName", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("borderEnableAutoHide", false).setType(Attribute_1.Attribute.BOOLEAN);
        return attributeDefinitions;
    }
    /**
     * 'private' constructor. Use the static method Model.fromJson(json) to create a model
     *  @internal
     */
    constructor() {
        /** @internal */
        this._borderRects = { inner: Rect_1.Rect.empty(), outer: Rect_1.Rect.empty() };
        this._attributes = {};
        this._idMap = {};
        this._borders = new BorderSet_1.BorderSet(this);
        this._pointerFine = true;
        this._showHiddenBorder = DockLocation_1.DockLocation.CENTER;
    }
    /** @internal */
    _setChangeListener(listener) {
        this._changeListener = listener;
    }
    /**
     * Get the currently active tabset node
     */
    getActiveTabset() {
        if (this._activeTabSet && this.getNodeById(this._activeTabSet.getId())) {
            return this._activeTabSet;
        }
        else {
            return undefined;
        }
    }
    /** @internal */
    _getShowHiddenBorder() {
        return this._showHiddenBorder;
    }
    /** @internal */
    _setShowHiddenBorder(location) {
        this._showHiddenBorder = location;
    }
    /** @internal */
    _setActiveTabset(tabsetNode) {
        this._activeTabSet = tabsetNode;
    }
    /**
     * Get the currently maximized tabset node
     */
    getMaximizedTabset() {
        return this._maximizedTabSet;
    }
    /** @internal */
    _setMaximizedTabset(tabsetNode) {
        this._maximizedTabSet = tabsetNode;
    }
    /**
     * Gets the root RowNode of the model
     * @returns {RowNode}
     */
    getRoot() {
        return this._root;
    }
    isRootOrientationVertical() {
        return this._attributes.rootOrientationVertical;
    }
    isUseVisibility() {
        return this._attributes.enableUseVisibility;
    }
    isEnableRotateBorderIcons() {
        return this._attributes.enableRotateBorderIcons;
    }
    /**
     * Gets the
     * @returns {BorderSet|*}
     */
    getBorderSet() {
        return this._borders;
    }
    /** @internal */
    _getOuterInnerRects() {
        return this._borderRects;
    }
    /** @internal */
    _getPointerFine() {
        return this._pointerFine;
    }
    /** @internal */
    _setPointerFine(pointerFine) {
        this._pointerFine = pointerFine;
    }
    /**
     * Visits all the nodes in the model and calls the given function for each
     * @param fn a function that takes visited node and a integer level as parameters
     */
    visitNodes(fn) {
        this._borders._forEachNode(fn);
        this._root._forEachNode(fn, 0);
    }
    /**
     * Gets a node by its id
     * @param id the id to find
     */
    getNodeById(id) {
        return this._idMap[id];
    }
    /**
     * Finds the first/top left tab set of the given node.
     * @param node The top node you want to begin searching from, deafults to the root node
     * @returns The first Tab Set
     */
    getFirstTabSet(node = this._root) {
        const child = node.getChildren()[0];
        if (child instanceof TabSetNode_1.TabSetNode) {
            return child;
        }
        else {
            return this.getFirstTabSet(child);
        }
    }
    /**
     * Update the node tree by performing the given action,
     * Actions should be generated via static methods on the Actions class
     * @param action the action to perform
     * @returns added Node for Actions.addNode; undefined otherwise
     */
    doAction(action) {
        let returnVal = undefined;
        // console.log(action);
        switch (action.type) {
            case Actions_1.Actions.ADD_NODE: {
                const newNode = new TabNode_1.TabNode(this, action.data.json, true);
                const toNode = this._idMap[action.data.toNode];
                if (toNode instanceof TabSetNode_1.TabSetNode || toNode instanceof BorderNode_1.BorderNode || toNode instanceof RowNode_1.RowNode) {
                    toNode.drop(newNode, DockLocation_1.DockLocation.getByName(action.data.location), action.data.index, action.data.select);
                    returnVal = newNode;
                }
                break;
            }
            case Actions_1.Actions.MOVE_NODE: {
                const fromNode = this._idMap[action.data.fromNode];
                if (fromNode instanceof TabNode_1.TabNode || fromNode instanceof TabSetNode_1.TabSetNode) {
                    const toNode = this._idMap[action.data.toNode];
                    if (toNode instanceof TabSetNode_1.TabSetNode || toNode instanceof BorderNode_1.BorderNode || toNode instanceof RowNode_1.RowNode) {
                        toNode.drop(fromNode, DockLocation_1.DockLocation.getByName(action.data.location), action.data.index, action.data.select);
                    }
                }
                break;
            }
            case Actions_1.Actions.DELETE_TAB: {
                const node = this._idMap[action.data.node];
                if (node instanceof TabNode_1.TabNode) {
                    node._delete();
                }
                break;
            }
            case Actions_1.Actions.DELETE_TABSET: {
                const node = this._idMap[action.data.node];
                if (node instanceof TabSetNode_1.TabSetNode) {
                    // first delete all child tabs that are closeable
                    const children = [...node.getChildren()];
                    for (let i = 0; i < children.length; i++) {
                        const child = children[i];
                        if (child.isEnableClose()) {
                            child._delete();
                        }
                    }
                    if (node.getChildren().length === 0) {
                        node._delete();
                    }
                    this._tidy();
                }
                break;
            }
            case Actions_1.Actions.FLOAT_TAB: {
                const node = this._idMap[action.data.node];
                if (node instanceof TabNode_1.TabNode) {
                    node._setFloating(true);
                    (0, Utils_1.adjustSelectedIndexAfterFloat)(node);
                }
                break;
            }
            case Actions_1.Actions.UNFLOAT_TAB: {
                const node = this._idMap[action.data.node];
                if (node instanceof TabNode_1.TabNode) {
                    node._setFloating(false);
                    (0, Utils_1.adjustSelectedIndexAfterDock)(node);
                }
                break;
            }
            case Actions_1.Actions.RENAME_TAB: {
                const node = this._idMap[action.data.node];
                if (node instanceof TabNode_1.TabNode) {
                    node._setName(action.data.text);
                }
                break;
            }
            case Actions_1.Actions.SELECT_TAB: {
                const tabNode = this._idMap[action.data.tabNode];
                if (tabNode instanceof TabNode_1.TabNode) {
                    const parent = tabNode.getParent();
                    const pos = parent.getChildren().indexOf(tabNode);
                    if (parent instanceof BorderNode_1.BorderNode) {
                        if (parent.getSelected() === pos) {
                            parent._setSelected(-1);
                        }
                        else {
                            parent._setSelected(pos);
                        }
                    }
                    else if (parent instanceof TabSetNode_1.TabSetNode) {
                        if (parent.getSelected() !== pos) {
                            parent._setSelected(pos);
                        }
                        this._activeTabSet = parent;
                    }
                }
                break;
            }
            case Actions_1.Actions.SET_ACTIVE_TABSET: {
                if (action.data.tabsetNode === undefined) {
                    this._activeTabSet = undefined;
                }
                else {
                    const tabsetNode = this._idMap[action.data.tabsetNode];
                    if (tabsetNode instanceof TabSetNode_1.TabSetNode) {
                        this._activeTabSet = tabsetNode;
                    }
                }
                break;
            }
            case Actions_1.Actions.ADJUST_SPLIT: {
                const node1 = this._idMap[action.data.node1];
                const node2 = this._idMap[action.data.node2];
                if ((node1 instanceof TabSetNode_1.TabSetNode || node1 instanceof RowNode_1.RowNode) && (node2 instanceof TabSetNode_1.TabSetNode || node2 instanceof RowNode_1.RowNode)) {
                    this._adjustSplitSide(node1, action.data.weight1, action.data.pixelWidth1);
                    this._adjustSplitSide(node2, action.data.weight2, action.data.pixelWidth2);
                }
                break;
            }
            case Actions_1.Actions.ADJUST_BORDER_SPLIT: {
                const node = this._idMap[action.data.node];
                if (node instanceof BorderNode_1.BorderNode) {
                    node._setSize(action.data.pos);
                }
                break;
            }
            case Actions_1.Actions.MAXIMIZE_TOGGLE: {
                const node = this._idMap[action.data.node];
                if (node instanceof TabSetNode_1.TabSetNode) {
                    if (node === this._maximizedTabSet) {
                        this._maximizedTabSet = undefined;
                    }
                    else {
                        this._maximizedTabSet = node;
                        this._activeTabSet = node;
                    }
                }
                break;
            }
            case Actions_1.Actions.UPDATE_MODEL_ATTRIBUTES: {
                this._updateAttrs(action.data.json);
                break;
            }
            case Actions_1.Actions.UPDATE_NODE_ATTRIBUTES: {
                const node = this._idMap[action.data.node];
                node._updateAttrs(action.data.json);
                break;
            }
            default:
                break;
        }
        this._updateIdMap();
        if (this._changeListener !== undefined) {
            this._changeListener(action);
        }
        return returnVal;
    }
    /** @internal */
    _updateIdMap() {
        // regenerate idMap to stop it building up
        this._idMap = {};
        this.visitNodes((node) => (this._idMap[node.getId()] = node));
        // console.log(JSON.stringify(Object.keys(this._idMap)));
    }
    /** @internal */
    _adjustSplitSide(node, weight, pixels) {
        node._setWeight(weight);
        if (node.getWidth() != null && node.getOrientation() === Orientation_1.Orientation.VERT) {
            node._updateAttrs({ width: pixels });
        }
        else if (node.getHeight() != null && node.getOrientation() === Orientation_1.Orientation.HORZ) {
            node._updateAttrs({ height: pixels });
        }
    }
    /**
     * Converts the model to a json object
     * @returns {IJsonModel} json object that represents this model
     */
    toJson() {
        const global = {};
        Model._attributeDefinitions.toJson(global, this._attributes);
        // save state of nodes
        this.visitNodes((node) => {
            node._fireEvent("save", undefined);
        });
        return { global, borders: this._borders._toJson(), layout: this._root.toJson() };
    }
    getSplitterSize() {
        let splitterSize = this._attributes.splitterSize;
        if (splitterSize === -1) {
            // use defaults
            splitterSize = this._pointerFine ? 8 : 12; // larger for mobile
        }
        return splitterSize;
    }
    isLegacyOverflowMenu() {
        return this._attributes.legacyOverflowMenu;
    }
    getSplitterExtra() {
        return this._attributes.splitterExtra;
    }
    isEnableEdgeDock() {
        return this._attributes.enableEdgeDock;
    }
    /** @internal */
    _addNode(node) {
        const id = node.getId();
        if (this._idMap[id] !== undefined) {
            throw new Error(`Error: each node must have a unique id, duplicate id:${node.getId()}`);
        }
        if (node.getType() !== "splitter") {
            this._idMap[id] = node;
        }
    }
    /** @internal */
    _layout(rect, metrics) {
        var _a;
        // let start = Date.now();
        this._borderRects = this._borders._layoutBorder({ outer: rect, inner: rect }, metrics);
        rect = this._borderRects.inner.removeInsets(this._getAttribute("marginInsets"));
        (_a = this._root) === null || _a === void 0 ? void 0 : _a.calcMinSize();
        this._root._layout(rect, metrics);
        // console.log("layout time: " + (Date.now() - start));
        return rect;
    }
    /** @internal */
    _findDropTargetNode(dragNode, x, y) {
        let node = this._root._findDropTargetNode(dragNode, x, y);
        if (node === undefined) {
            node = this._borders._findDropTargetNode(dragNode, x, y);
        }
        return node;
    }
    /** @internal */
    _tidy() {
        // console.log("before _tidy", this.toString());
        this._root._tidy();
        // console.log("after _tidy", this.toString());
    }
    /** @internal */
    _updateAttrs(json) {
        Model._attributeDefinitions.update(json, this._attributes);
    }
    /** @internal */
    _nextUniqueId() {
        return '#' + (0, Utils_1.randomUUID)();
    }
    /** @internal */
    _getAttribute(name) {
        return this._attributes[name];
    }
    /**
     * Sets a function to allow/deny dropping a node
     * @param onAllowDrop function that takes the drag node and DropInfo and returns true if the drop is allowed
     */
    setOnAllowDrop(onAllowDrop) {
        this._onAllowDrop = onAllowDrop;
    }
    /** @internal */
    _getOnAllowDrop() {
        return this._onAllowDrop;
    }
    /**
     * set callback called when a new TabSet is created.
     * The tabNode can be undefined if it's the auto created first tabset in the root row (when the last
     * tab is deleted, the root tabset can be recreated)
     * @param onCreateTabSet
     */
    setOnCreateTabSet(onCreateTabSet) {
        this._onCreateTabSet = onCreateTabSet;
    }
    /** @internal */
    _getOnCreateTabSet() {
        return this._onCreateTabSet;
    }
    static toTypescriptInterfaces() {
        console.log(Model._attributeDefinitions.toTypescriptInterface("Global", undefined));
        console.log(RowNode_1.RowNode.getAttributeDefinitions().toTypescriptInterface("Row", Model._attributeDefinitions));
        console.log(TabSetNode_1.TabSetNode.getAttributeDefinitions().toTypescriptInterface("TabSet", Model._attributeDefinitions));
        console.log(TabNode_1.TabNode.getAttributeDefinitions().toTypescriptInterface("Tab", Model._attributeDefinitions));
        console.log(BorderNode_1.BorderNode.getAttributeDefinitions().toTypescriptInterface("Border", Model._attributeDefinitions));
    }
    toString() {
        return JSON.stringify(this.toJson());
    }
}
exports.Model = Model;
/** @internal */
Model._attributeDefinitions = Model._createAttributeDefinitions();
//# sourceMappingURL=Model.js.map

/***/ }),

/***/ 7437:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AH: function() { return /* binding */ css; },
/* harmony export */   i7: function() { return /* binding */ keyframes; },
/* harmony export */   mL: function() { return /* binding */ Global; }
/* harmony export */ });
/* unused harmony exports ClassNames, createElement, jsx */
/* harmony import */ var _emotion_element_f0de968e_browser_esm_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4684);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6540);
/* harmony import */ var _emotion_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(41);
/* harmony import */ var _emotion_use_insertion_effect_with_fallbacks__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1287);
/* harmony import */ var _emotion_serialize__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3174);
/* harmony import */ var _emotion_cache__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5655);
/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4146);
/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_6__);












var jsx = function jsx(type, props) {
  // eslint-disable-next-line prefer-rest-params
  var args = arguments;

  if (props == null || !_emotion_element_f0de968e_browser_esm_js__WEBPACK_IMPORTED_MODULE_0__.h.call(props, 'css')) {
    return react__WEBPACK_IMPORTED_MODULE_1__.createElement.apply(undefined, args);
  }

  var argsLength = args.length;
  var createElementArgArray = new Array(argsLength);
  createElementArgArray[0] = _emotion_element_f0de968e_browser_esm_js__WEBPACK_IMPORTED_MODULE_0__.E;
  createElementArgArray[1] = (0,_emotion_element_f0de968e_browser_esm_js__WEBPACK_IMPORTED_MODULE_0__.c)(type, props);

  for (var i = 2; i < argsLength; i++) {
    createElementArgArray[i] = args[i];
  }

  return react__WEBPACK_IMPORTED_MODULE_1__.createElement.apply(null, createElementArgArray);
};

(function (_jsx) {
  var JSX;

  (function (_JSX) {})(JSX || (JSX = _jsx.JSX || (_jsx.JSX = {})));
})(jsx || (jsx = {}));

// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag

var Global = /* #__PURE__ */(0,_emotion_element_f0de968e_browser_esm_js__WEBPACK_IMPORTED_MODULE_0__.w)(function (props, cache) {

  var styles = props.styles;
  var serialized = (0,_emotion_serialize__WEBPACK_IMPORTED_MODULE_4__/* .serializeStyles */ .J)([styles], undefined, react__WEBPACK_IMPORTED_MODULE_1__.useContext(_emotion_element_f0de968e_browser_esm_js__WEBPACK_IMPORTED_MODULE_0__.T));
  // but it is based on a constant that will never change at runtime
  // it's effectively like having two implementations and switching them out
  // so it's not actually breaking anything


  var sheetRef = react__WEBPACK_IMPORTED_MODULE_1__.useRef();
  (0,_emotion_use_insertion_effect_with_fallbacks__WEBPACK_IMPORTED_MODULE_3__/* .useInsertionEffectWithLayoutFallback */ .i)(function () {
    var key = cache.key + "-global"; // use case of https://github.com/emotion-js/emotion/issues/2675

    var sheet = new cache.sheet.constructor({
      key: key,
      nonce: cache.sheet.nonce,
      container: cache.sheet.container,
      speedy: cache.sheet.isSpeedy
    });
    var rehydrating = false;
    var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]");

    if (cache.sheet.tags.length) {
      sheet.before = cache.sheet.tags[0];
    }

    if (node !== null) {
      rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other <Global/>s

      node.setAttribute('data-emotion', key);
      sheet.hydrate([node]);
    }

    sheetRef.current = [sheet, rehydrating];
    return function () {
      sheet.flush();
    };
  }, [cache]);
  (0,_emotion_use_insertion_effect_with_fallbacks__WEBPACK_IMPORTED_MODULE_3__/* .useInsertionEffectWithLayoutFallback */ .i)(function () {
    var sheetRefCurrent = sheetRef.current;
    var sheet = sheetRefCurrent[0],
        rehydrating = sheetRefCurrent[1];

    if (rehydrating) {
      sheetRefCurrent[1] = false;
      return;
    }

    if (serialized.next !== undefined) {
      // insert keyframes
      (0,_emotion_utils__WEBPACK_IMPORTED_MODULE_2__/* .insertStyles */ .sk)(cache, serialized.next, true);
    }

    if (sheet.tags.length) {
      // if this doesn't exist then it will be null so the style element will be appended
      var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
      sheet.before = element;
      sheet.flush();
    }

    cache.insert("", serialized, sheet, false);
  }, [cache, serialized.name]);
  return null;
});

function css() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return (0,_emotion_serialize__WEBPACK_IMPORTED_MODULE_4__/* .serializeStyles */ .J)(args);
}

function keyframes() {
  var insertable = css.apply(void 0, arguments);
  var name = "animation-" + insertable.name;
  return {
    name: name,
    styles: "@keyframes " + name + "{" + insertable.styles + "}",
    anim: 1,
    toString: function toString() {
      return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
    }
  };
}

var classnames = function classnames(args) {
  var len = args.length;
  var i = 0;
  var cls = '';

  for (; i < len; i++) {
    var arg = args[i];
    if (arg == null) continue;
    var toAdd = void 0;

    switch (typeof arg) {
      case 'boolean':
        break;

      case 'object':
        {
          if (Array.isArray(arg)) {
            toAdd = classnames(arg);
          } else {

            toAdd = '';

            for (var k in arg) {
              if (arg[k] && k) {
                toAdd && (toAdd += ' ');
                toAdd += k;
              }
            }
          }

          break;
        }

      default:
        {
          toAdd = arg;
        }
    }

    if (toAdd) {
      cls && (cls += ' ');
      cls += toAdd;
    }
  }

  return cls;
};

function merge(registered, css, className) {
  var registeredStyles = [];
  var rawClassName = getRegisteredStyles(registered, registeredStyles, className);

  if (registeredStyles.length < 2) {
    return className;
  }

  return rawClassName + css(registeredStyles);
}

var Insertion = function Insertion(_ref) {
  var cache = _ref.cache,
      serializedArr = _ref.serializedArr;
  useInsertionEffectAlwaysWithSyncFallback(function () {

    for (var i = 0; i < serializedArr.length; i++) {
      insertStyles(cache, serializedArr[i], false);
    }
  });

  return null;
};

var ClassNames = /* #__PURE__ */(/* unused pure expression or super */ null && (withEmotionCache(function (props, cache) {
  var hasRendered = false;
  var serializedArr = [];

  var css = function css() {
    if (hasRendered && isDevelopment) {
      throw new Error('css can only be used during render');
    }

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var serialized = serializeStyles(args, cache.registered);
    serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`

    registerStyles(cache, serialized, false);
    return cache.key + "-" + serialized.name;
  };

  var cx = function cx() {
    if (hasRendered && isDevelopment) {
      throw new Error('cx can only be used during render');
    }

    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }

    return merge(cache.registered, css, classnames(args));
  };

  var content = {
    css: css,
    cx: cx,
    theme: React.useContext(ThemeContext)
  };
  var ele = props.children(content);
  hasRendered = true;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Insertion, {
    cache: cache,
    serializedArr: serializedArr
  }), ele);
})));




/***/ }),

/***/ 7462:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Layout = void 0;
const React = __webpack_require__(6540);
const react_dom_1 = __webpack_require__(961);
const DockLocation_1 = __webpack_require__(8324);
const DragDrop_1 = __webpack_require__(883);
const Actions_1 = __webpack_require__(9103);
const BorderNode_1 = __webpack_require__(1480);
const SplitterNode_1 = __webpack_require__(6169);
const TabNode_1 = __webpack_require__(8171);
const TabSetNode_1 = __webpack_require__(9555);
const Rect_1 = __webpack_require__(2530);
const Types_1 = __webpack_require__(6643);
const BorderTabSet_1 = __webpack_require__(4767);
const Splitter_1 = __webpack_require__(2439);
const Tab_1 = __webpack_require__(9425);
const TabSet_1 = __webpack_require__(1809);
const FloatingWindow_1 = __webpack_require__(94);
const FloatingWindowTab_1 = __webpack_require__(7515);
const TabFloating_1 = __webpack_require__(3203);
const Orientation_1 = __webpack_require__(1648);
const Icons_1 = __webpack_require__(8636);
const TabButtonStamp_1 = __webpack_require__(2486);
const defaultIcons = {
    close: React.createElement(Icons_1.CloseIcon, null),
    closeTabset: React.createElement(Icons_1.CloseIcon, null),
    popout: React.createElement(Icons_1.PopoutIcon, null),
    maximize: React.createElement(Icons_1.MaximizeIcon, null),
    restore: React.createElement(Icons_1.RestoreIcon, null),
    more: React.createElement(Icons_1.OverflowIcon, null),
    edgeArrow: React.createElement(Icons_1.EdgeIcon, null)
};
// Popout windows work in latest browsers based on webkit (Chrome, Opera, Safari, latest Edge) and Firefox. They do
// not work on any version if IE or the original Edge browser
// Assume any recent desktop browser not IE or original Edge will work
/** @internal */
// @ts-ignore
const isIEorEdge = typeof window !== "undefined" && (window.document.documentMode || /Edge\//.test(window.navigator.userAgent));
/** @internal */
const isDesktop = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(hover: hover) and (pointer: fine)").matches;
/** @internal */
const defaultSupportsPopout = isDesktop && !isIEorEdge;
/**
 * A React component that hosts a multi-tabbed layout
 */
class Layout extends React.Component {
    constructor(props) {
        super(props);
        /** @internal */
        this.firstMove = false;
        /** @internal */
        this.dragRectRendered = true;
        /** @internal */
        this.dragDivText = undefined;
        /** @internal */
        this.edgeRectLength = 100;
        /** @internal */
        this.edgeRectWidth = 10;
        /** @internal */
        this.onModelChange = (action) => {
            this.forceUpdate();
            if (this.props.onModelChange) {
                this.props.onModelChange(this.props.model, action);
            }
        };
        /** @internal */
        this.updateRect = (domRect) => {
            if (!domRect) {
                domRect = this.getDomRect();
            }
            if (!domRect) {
                // no dom rect available, return.
                return;
            }
            const rect = new Rect_1.Rect(0, 0, domRect.width, domRect.height);
            if (!rect.equals(this.state.rect) && rect.width !== 0 && rect.height !== 0) {
                this.setState({ rect });
            }
        };
        /** @internal */
        this.updateLayoutMetrics = () => {
            if (this.findHeaderBarSizeRef.current) {
                const headerBarSize = this.findHeaderBarSizeRef.current.getBoundingClientRect().height;
                if (headerBarSize !== this.state.calculatedHeaderBarSize) {
                    this.setState({ calculatedHeaderBarSize: headerBarSize });
                }
            }
            if (this.findTabBarSizeRef.current) {
                const tabBarSize = this.findTabBarSizeRef.current.getBoundingClientRect().height;
                if (tabBarSize !== this.state.calculatedTabBarSize) {
                    this.setState({ calculatedTabBarSize: tabBarSize });
                }
            }
            if (this.findBorderBarSizeRef.current) {
                const borderBarSize = this.findBorderBarSizeRef.current.getBoundingClientRect().height;
                if (borderBarSize !== this.state.calculatedBorderBarSize) {
                    this.setState({ calculatedBorderBarSize: borderBarSize });
                }
            }
        };
        /** @internal */
        this.getClassName = (defaultClassName) => {
            if (this.props.classNameMapper === undefined) {
                return defaultClassName;
            }
            else {
                return this.props.classNameMapper(defaultClassName);
            }
        };
        /** @internal */
        this.onCloseWindow = (id) => {
            this.doAction(Actions_1.Actions.unFloatTab(id));
            try {
                this.props.model.getNodeById(id)._setWindow(undefined);
            }
            catch (e) {
                // catch incase it was a model change
            }
        };
        /** @internal */
        this.onSetWindow = (id, window) => {
            this.props.model.getNodeById(id)._setWindow(window);
        };
        /** @internal */
        this.onCancelAdd = () => {
            var _a, _b;
            const rootdiv = this.selfRef.current;
            if (rootdiv && this.dragDiv) {
                rootdiv.removeChild(this.dragDiv);
            }
            this.dragDiv = undefined;
            this.hidePortal();
            if (this.fnNewNodeDropped != null) {
                this.fnNewNodeDropped();
                this.fnNewNodeDropped = undefined;
            }
            try {
                (_b = (_a = this.customDrop) === null || _a === void 0 ? void 0 : _a.invalidated) === null || _b === void 0 ? void 0 : _b.call(_a);
            }
            catch (e) {
                console.error(e);
            }
            DragDrop_1.DragDrop.instance.hideGlass();
            this.newTabJson = undefined;
            this.customDrop = undefined;
        };
        /** @internal */
        this.onCancelDrag = (wasDragging) => {
            var _a, _b;
            if (wasDragging) {
                const rootdiv = this.selfRef.current;
                const outlineDiv = this.outlineDiv;
                if (rootdiv && outlineDiv) {
                    try {
                        rootdiv.removeChild(outlineDiv);
                    }
                    catch (e) { }
                }
                const dragDiv = this.dragDiv;
                if (rootdiv && dragDiv) {
                    try {
                        rootdiv.removeChild(dragDiv);
                    }
                    catch (e) { }
                }
                this.dragDiv = undefined;
                this.hidePortal();
                this.setState({ showEdges: false });
                if (this.fnNewNodeDropped != null) {
                    this.fnNewNodeDropped();
                    this.fnNewNodeDropped = undefined;
                }
                try {
                    (_b = (_a = this.customDrop) === null || _a === void 0 ? void 0 : _a.invalidated) === null || _b === void 0 ? void 0 : _b.call(_a);
                }
                catch (e) {
                    console.error(e);
                }
                DragDrop_1.DragDrop.instance.hideGlass();
                this.newTabJson = undefined;
                this.customDrop = undefined;
            }
            this.setState({ showHiddenBorder: DockLocation_1.DockLocation.CENTER });
        };
        /** @internal */
        this.onDragDivMouseDown = (event) => {
            event.preventDefault();
            this.dragStart(event, this.dragDivText, TabNode_1.TabNode._fromJson(this.newTabJson, this.props.model, false), true, undefined, undefined);
        };
        /** @internal */
        this.dragStart = (event, dragDivText, node, allowDrag, onClick, onDoubleClick) => {
            var _a, _b;
            if (!allowDrag) {
                DragDrop_1.DragDrop.instance.startDrag(event, undefined, undefined, undefined, undefined, onClick, onDoubleClick, this.currentDocument, (_a = this.selfRef.current) !== null && _a !== void 0 ? _a : undefined);
            }
            else {
                this.dragNode = node;
                this.dragDivText = dragDivText;
                DragDrop_1.DragDrop.instance.startDrag(event, this.onDragStart, this.onDragMove, this.onDragEnd, this.onCancelDrag, onClick, onDoubleClick, this.currentDocument, (_b = this.selfRef.current) !== null && _b !== void 0 ? _b : undefined);
            }
        };
        /** @internal */
        this.dragRectRender = (text, node, json, onRendered) => {
            let content;
            if (text !== undefined) {
                content = React.createElement("div", { style: { whiteSpace: "pre" } }, text.replace("<br>", "\n"));
            }
            else {
                if (node && node instanceof TabNode_1.TabNode) {
                    content = (React.createElement(TabButtonStamp_1.TabButtonStamp, { node: node, layout: this, iconFactory: this.props.iconFactory, titleFactory: this.props.titleFactory }));
                }
            }
            if (this.props.onRenderDragRect !== undefined) {
                const customContent = this.props.onRenderDragRect(content, node, json);
                if (customContent !== undefined) {
                    content = customContent;
                }
            }
            // hide div until the render is complete
            this.dragRectRendered = false;
            const dragDiv = this.dragDiv;
            if (dragDiv) {
                dragDiv.style.visibility = "hidden";
                this.showPortal(React.createElement(DragRectRenderWrapper
                // wait for it to be rendered
                , { 
                    // wait for it to be rendered
                    onRendered: () => {
                        this.dragRectRendered = true;
                        onRendered === null || onRendered === void 0 ? void 0 : onRendered();
                    } }, content), dragDiv);
            }
        };
        /** @internal */
        this.showPortal = (control, element) => {
            const portal = (0, react_dom_1.createPortal)(control, element);
            this.setState({ portal });
        };
        /** @internal */
        this.hidePortal = () => {
            this.setState({ portal: undefined });
        };
        /** @internal */
        this.onDragStart = () => {
            var _a;
            this.dropInfo = undefined;
            this.customDrop = undefined;
            const rootdiv = this.selfRef.current;
            this.outlineDiv = this.currentDocument.createElement("div");
            this.outlineDiv.className = this.getClassName(Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
            this.outlineDiv.style.visibility = "hidden";
            if (rootdiv) {
                rootdiv.appendChild(this.outlineDiv);
            }
            if (this.dragDiv == null) {
                this.dragDiv = this.currentDocument.createElement("div");
                this.dragDiv.className = this.getClassName(Types_1.CLASSES.FLEXLAYOUT__DRAG_RECT);
                this.dragDiv.setAttribute("data-layout-path", "/drag-rectangle");
                this.dragRectRender(this.dragDivText, this.dragNode, this.newTabJson);
                if (rootdiv) {
                    rootdiv.appendChild(this.dragDiv);
                }
            }
            // add edge indicators
            if (this.props.model.getMaximizedTabset() === undefined) {
                this.setState({ showEdges: this.props.model.isEnableEdgeDock() });
            }
            if (this.dragNode && this.outlineDiv && this.dragNode instanceof TabNode_1.TabNode && this.dragNode.getTabRect() !== undefined) {
                (_a = this.dragNode.getTabRect()) === null || _a === void 0 ? void 0 : _a.positionElement(this.outlineDiv);
            }
            this.firstMove = true;
            return true;
        };
        /** @internal */
        this.onDragMove = (event) => {
            var _a, _b, _c, _d, _e, _f, _g;
            if (this.firstMove === false) {
                const speed = this.props.model._getAttribute("tabDragSpeed");
                if (this.outlineDiv) {
                    this.outlineDiv.style.transition = `top ${speed}s, left ${speed}s, width ${speed}s, height ${speed}s`;
                }
            }
            this.firstMove = false;
            const clientRect = (_a = this.selfRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
            const pos = {
                x: event.clientX - ((_b = clientRect === null || clientRect === void 0 ? void 0 : clientRect.left) !== null && _b !== void 0 ? _b : 0),
                y: event.clientY - ((_c = clientRect === null || clientRect === void 0 ? void 0 : clientRect.top) !== null && _c !== void 0 ? _c : 0),
            };
            this.checkForBorderToShow(pos.x, pos.y);
            // keep it between left & right
            const dragRect = (_e = (_d = this.dragDiv) === null || _d === void 0 ? void 0 : _d.getBoundingClientRect()) !== null && _e !== void 0 ? _e : new DOMRect(0, 0, 100, 100);
            let newLeft = pos.x - dragRect.width / 2;
            if (newLeft + dragRect.width > ((_f = clientRect === null || clientRect === void 0 ? void 0 : clientRect.width) !== null && _f !== void 0 ? _f : 0)) {
                newLeft = ((_g = clientRect === null || clientRect === void 0 ? void 0 : clientRect.width) !== null && _g !== void 0 ? _g : 0) - dragRect.width;
            }
            newLeft = Math.max(0, newLeft);
            if (this.dragDiv) {
                this.dragDiv.style.left = newLeft + "px";
                this.dragDiv.style.top = pos.y + 5 + "px";
                if (this.dragRectRendered && this.dragDiv.style.visibility === "hidden") {
                    // make visible once the drag rect has been rendered
                    this.dragDiv.style.visibility = "visible";
                }
            }
            let dropInfo = this.props.model._findDropTargetNode(this.dragNode, pos.x, pos.y);
            if (dropInfo) {
                if (this.props.onTabDrag) {
                    this.handleCustomTabDrag(dropInfo, pos, event);
                }
                else {
                    this.dropInfo = dropInfo;
                    if (this.outlineDiv) {
                        this.outlineDiv.className = this.getClassName(dropInfo.className);
                        dropInfo.rect.positionElement(this.outlineDiv);
                        this.outlineDiv.style.visibility = "visible";
                    }
                }
            }
        };
        /** @internal */
        this.onDragEnd = (event) => {
            const rootdiv = this.selfRef.current;
            if (rootdiv) {
                if (this.outlineDiv) {
                    rootdiv.removeChild(this.outlineDiv);
                }
                if (this.dragDiv) {
                    rootdiv.removeChild(this.dragDiv);
                }
            }
            this.dragDiv = undefined;
            this.hidePortal();
            this.setState({ showEdges: false });
            DragDrop_1.DragDrop.instance.hideGlass();
            if (this.dropInfo) {
                if (this.customDrop) {
                    this.newTabJson = undefined;
                    try {
                        const { callback, dragging, over, x, y, location } = this.customDrop;
                        callback(dragging, over, x, y, location);
                        if (this.fnNewNodeDropped != null) {
                            this.fnNewNodeDropped();
                            this.fnNewNodeDropped = undefined;
                        }
                    }
                    catch (e) {
                        console.error(e);
                    }
                }
                else if (this.newTabJson !== undefined) {
                    const newNode = this.doAction(Actions_1.Actions.addNode(this.newTabJson, this.dropInfo.node.getId(), this.dropInfo.location, this.dropInfo.index));
                    if (this.fnNewNodeDropped != null) {
                        this.fnNewNodeDropped(newNode, event);
                        this.fnNewNodeDropped = undefined;
                    }
                    this.newTabJson = undefined;
                }
                else if (this.dragNode !== undefined) {
                    this.doAction(Actions_1.Actions.moveNode(this.dragNode.getId(), this.dropInfo.node.getId(), this.dropInfo.location, this.dropInfo.index));
                }
            }
            this.setState({ showHiddenBorder: DockLocation_1.DockLocation.CENTER });
        };
        this.props.model._setChangeListener(this.onModelChange);
        this.tabIds = [];
        this.selfRef = React.createRef();
        this.findHeaderBarSizeRef = React.createRef();
        this.findTabBarSizeRef = React.createRef();
        this.findBorderBarSizeRef = React.createRef();
        this.supportsPopout = props.supportsPopout !== undefined ? props.supportsPopout : defaultSupportsPopout;
        this.popoutURL = props.popoutURL ? props.popoutURL : "popout.html";
        this.icons = Object.assign(Object.assign({}, defaultIcons), props.icons);
        this.state = {
            rect: new Rect_1.Rect(0, 0, 0, 0),
            calculatedHeaderBarSize: 25,
            calculatedTabBarSize: 26,
            calculatedBorderBarSize: 30,
            editingTab: undefined,
            showHiddenBorder: DockLocation_1.DockLocation.CENTER,
            showEdges: false,
        };
        this.onDragEnter = this.onDragEnter.bind(this);
    }
    /** @internal */
    styleFont(style) {
        if (this.props.font) {
            if (this.selfRef.current) {
                if (this.props.font.size) {
                    this.selfRef.current.style.setProperty("--font-size", this.props.font.size);
                }
                if (this.props.font.family) {
                    this.selfRef.current.style.setProperty("--font-family", this.props.font.family);
                }
            }
            if (this.props.font.style) {
                style.fontStyle = this.props.font.style;
            }
            if (this.props.font.weight) {
                style.fontWeight = this.props.font.weight;
            }
        }
        return style;
    }
    /** @internal */
    doAction(action) {
        if (this.props.onAction !== undefined) {
            const outcome = this.props.onAction(action);
            if (outcome !== undefined) {
                return this.props.model.doAction(outcome);
            }
            return undefined;
        }
        else {
            return this.props.model.doAction(action);
        }
    }
    /** @internal */
    componentDidMount() {
        this.updateRect();
        this.updateLayoutMetrics();
        // need to re-render if size changes
        this.currentDocument = this.selfRef.current.ownerDocument;
        this.currentWindow = this.currentDocument.defaultView;
        this.resizeObserver = new ResizeObserver(entries => {
            this.updateRect(entries[0].contentRect);
        });
        const selfRefCurr = this.selfRef.current;
        if (selfRefCurr) {
            this.resizeObserver.observe(selfRefCurr);
        }
    }
    /** @internal */
    componentDidUpdate() {
        this.updateLayoutMetrics();
        if (this.props.model !== this.previousModel) {
            if (this.previousModel !== undefined) {
                this.previousModel._setChangeListener(undefined); // stop listening to old model
            }
            this.props.model._setChangeListener(this.onModelChange);
            this.previousModel = this.props.model;
        }
        // console.log("Layout time: " + this.layoutTime + "ms Render time: " + (Date.now() - this.start) + "ms");
    }
    /** @internal */
    getCurrentDocument() {
        return this.currentDocument;
    }
    /** @internal */
    getDomRect() {
        var _a;
        return (_a = this.selfRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    }
    /** @internal */
    getRootDiv() {
        return this.selfRef.current;
    }
    /** @internal */
    isSupportsPopout() {
        return this.supportsPopout;
    }
    /** @internal */
    isRealtimeResize() {
        var _a;
        return (_a = this.props.realtimeResize) !== null && _a !== void 0 ? _a : false;
    }
    /** @internal */
    onTabDrag(...args) {
        var _a, _b;
        return (_b = (_a = this.props).onTabDrag) === null || _b === void 0 ? void 0 : _b.call(_a, ...args);
    }
    /** @internal */
    getPopoutURL() {
        return this.popoutURL;
    }
    /** @internal */
    componentWillUnmount() {
        var _a;
        const selfRefCurr = this.selfRef.current;
        if (selfRefCurr) {
            (_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.unobserve(selfRefCurr);
        }
    }
    /** @internal */
    setEditingTab(tabNode) {
        this.setState({ editingTab: tabNode });
    }
    /** @internal */
    getEditingTab() {
        return this.state.editingTab;
    }
    /** @internal */
    render() {
        // first render will be used to find the size (via selfRef)
        if (!this.selfRef.current) {
            return (React.createElement("div", { ref: this.selfRef, className: this.getClassName(Types_1.CLASSES.FLEXLAYOUT__LAYOUT) }, this.metricsElements()));
        }
        this.props.model._setPointerFine(window && window.matchMedia && window.matchMedia("(pointer: fine)").matches);
        // this.start = Date.now();
        const borderComponents = [];
        const tabSetComponents = [];
        const floatingWindows = [];
        const tabComponents = {};
        const splitterComponents = [];
        const metrics = {
            headerBarSize: this.state.calculatedHeaderBarSize,
            tabBarSize: this.state.calculatedTabBarSize,
            borderBarSize: this.state.calculatedBorderBarSize
        };
        this.props.model._setShowHiddenBorder(this.state.showHiddenBorder);
        this.centerRect = this.props.model._layout(this.state.rect, metrics);
        this.renderBorder(this.props.model.getBorderSet(), borderComponents, tabComponents, floatingWindows, splitterComponents);
        this.renderChildren("", this.props.model.getRoot(), tabSetComponents, tabComponents, floatingWindows, splitterComponents);
        const nextTopIds = [];
        const nextTopIdsMap = {};
        // Keep any previous tabs in the same DOM order as before, removing any that have been deleted
        for (const t of this.tabIds) {
            if (tabComponents[t]) {
                nextTopIds.push(t);
                nextTopIdsMap[t] = t;
            }
        }
        this.tabIds = nextTopIds;
        // Add tabs that have been added to the DOM
        for (const t of Object.keys(tabComponents)) {
            if (!nextTopIdsMap[t]) {
                this.tabIds.push(t);
            }
        }
        const edges = [];
        const arrowIcon = this.icons.edgeArrow;
        if (this.state.showEdges) {
            const r = this.centerRect;
            const length = this.edgeRectLength;
            const width = this.edgeRectWidth;
            const offset = this.edgeRectLength / 2;
            const className = this.getClassName(Types_1.CLASSES.FLEXLAYOUT__EDGE_RECT);
            const radius = 50;
            edges.push(React.createElement("div", { key: "North", style: { top: r.y, left: r.x + r.width / 2 - offset, width: length, height: width, borderBottomLeftRadius: radius, borderBottomRightRadius: radius }, className: className + " " + this.getClassName(Types_1.CLASSES.FLEXLAYOUT__EDGE_RECT_TOP) },
                React.createElement("div", { style: { transform: "rotate(180deg)" } }, arrowIcon)));
            edges.push(React.createElement("div", { key: "West", style: { top: r.y + r.height / 2 - offset, left: r.x, width: width, height: length, borderTopRightRadius: radius, borderBottomRightRadius: radius }, className: className + " " + this.getClassName(Types_1.CLASSES.FLEXLAYOUT__EDGE_RECT_LEFT) },
                React.createElement("div", { style: { transform: "rotate(90deg)" } }, arrowIcon)));
            edges.push(React.createElement("div", { key: "South", style: { top: r.y + r.height - width, left: r.x + r.width / 2 - offset, width: length, height: width, borderTopLeftRadius: radius, borderTopRightRadius: radius }, className: className + " " + this.getClassName(Types_1.CLASSES.FLEXLAYOUT__EDGE_RECT_BOTTOM) },
                React.createElement("div", null, arrowIcon)));
            edges.push(React.createElement("div", { key: "East", style: { top: r.y + r.height / 2 - offset, left: r.x + r.width - width, width: width, height: length, borderTopLeftRadius: radius, borderBottomLeftRadius: radius }, className: className + " " + this.getClassName(Types_1.CLASSES.FLEXLAYOUT__EDGE_RECT_RIGHT) },
                React.createElement("div", { style: { transform: "rotate(-90deg)" } }, arrowIcon)));
        }
        // this.layoutTime = (Date.now() - this.start);
        return (React.createElement("div", { ref: this.selfRef, className: this.getClassName(Types_1.CLASSES.FLEXLAYOUT__LAYOUT), onDragEnter: this.props.onExternalDrag ? this.onDragEnter : undefined },
            tabSetComponents,
            this.tabIds.map((t) => {
                return tabComponents[t];
            }),
            borderComponents,
            splitterComponents,
            edges,
            floatingWindows,
            this.metricsElements(),
            this.state.portal));
    }
    /** @internal */
    metricsElements() {
        // used to measure the tab and border tab sizes
        const fontStyle = this.styleFont({ visibility: "hidden" });
        return (React.createElement(React.Fragment, null,
            React.createElement("div", { key: "findHeaderBarSize", ref: this.findHeaderBarSizeRef, style: fontStyle, className: this.getClassName(Types_1.CLASSES.FLEXLAYOUT__TABSET_HEADER_SIZER) }, "FindHeaderBarSize"),
            React.createElement("div", { key: "findTabBarSize", ref: this.findTabBarSizeRef, style: fontStyle, className: this.getClassName(Types_1.CLASSES.FLEXLAYOUT__TABSET_SIZER) }, "FindTabBarSize"),
            React.createElement("div", { key: "findBorderBarSize", ref: this.findBorderBarSizeRef, style: fontStyle, className: this.getClassName(Types_1.CLASSES.FLEXLAYOUT__BORDER_SIZER) }, "FindBorderBarSize")));
    }
    /** @internal */
    renderBorder(borderSet, borderComponents, tabComponents, floatingWindows, splitterComponents) {
        for (const border of borderSet.getBorders()) {
            const borderPath = `/border/${border.getLocation().getName()}`;
            if (border.isShowing()) {
                borderComponents.push(React.createElement(BorderTabSet_1.BorderTabSet, { key: `border_${border.getLocation().getName()}`, path: borderPath, border: border, layout: this, iconFactory: this.props.iconFactory, titleFactory: this.props.titleFactory, icons: this.icons }));
                const drawChildren = border._getDrawChildren();
                let i = 0;
                let tabCount = 0;
                for (const child of drawChildren) {
                    if (child instanceof SplitterNode_1.SplitterNode) {
                        let path = borderPath + "/s";
                        splitterComponents.push(React.createElement(Splitter_1.Splitter, { key: child.getId(), layout: this, node: child, path: path }));
                    }
                    else if (child instanceof TabNode_1.TabNode) {
                        let path = borderPath + "/t" + tabCount++;
                        if (this.supportsPopout && child.isFloating()) {
                            const rect = this._getScreenRect(child);
                            const tabBorderWidth = child._getAttr("borderWidth");
                            const tabBorderHeight = child._getAttr("borderHeight");
                            if (rect) {
                                if (tabBorderWidth !== -1 && border.getLocation().getOrientation() === Orientation_1.Orientation.HORZ) {
                                    rect.width = tabBorderWidth;
                                }
                                else if (tabBorderHeight !== -1 && border.getLocation().getOrientation() === Orientation_1.Orientation.VERT) {
                                    rect.height = tabBorderHeight;
                                }
                            }
                            floatingWindows.push(React.createElement(FloatingWindow_1.FloatingWindow, { key: child.getId(), url: this.popoutURL, rect: rect, title: child.getName(), id: child.getId(), onSetWindow: this.onSetWindow, onCloseWindow: this.onCloseWindow },
                                React.createElement(FloatingWindowTab_1.FloatingWindowTab, { layout: this, node: child, factory: this.props.factory })));
                            tabComponents[child.getId()] = React.createElement(TabFloating_1.TabFloating, { key: child.getId(), layout: this, path: path, node: child, selected: i === border.getSelected() });
                        }
                        else {
                            tabComponents[child.getId()] = React.createElement(Tab_1.Tab, { key: child.getId(), layout: this, path: path, node: child, selected: i === border.getSelected(), factory: this.props.factory });
                        }
                    }
                    i++;
                }
            }
        }
    }
    /** @internal */
    renderChildren(path, node, tabSetComponents, tabComponents, floatingWindows, splitterComponents) {
        const drawChildren = node._getDrawChildren();
        let splitterCount = 0;
        let tabCount = 0;
        let rowCount = 0;
        for (const child of drawChildren) {
            if (child instanceof SplitterNode_1.SplitterNode) {
                const newPath = path + "/s" + (splitterCount++);
                splitterComponents.push(React.createElement(Splitter_1.Splitter, { key: child.getId(), layout: this, path: newPath, node: child }));
            }
            else if (child instanceof TabSetNode_1.TabSetNode) {
                const newPath = path + "/ts" + (rowCount++);
                tabSetComponents.push(React.createElement(TabSet_1.TabSet, { key: child.getId(), layout: this, path: newPath, node: child, iconFactory: this.props.iconFactory, titleFactory: this.props.titleFactory, icons: this.icons }));
                this.renderChildren(newPath, child, tabSetComponents, tabComponents, floatingWindows, splitterComponents);
            }
            else if (child instanceof TabNode_1.TabNode) {
                const newPath = path + "/t" + (tabCount++);
                const selectedTab = child.getParent().getChildren()[child.getParent().getSelected()];
                if (selectedTab === undefined) {
                    // this should not happen!
                    console.warn("undefined selectedTab should not happen");
                }
                if (this.supportsPopout && child.isFloating()) {
                    const rect = this._getScreenRect(child);
                    floatingWindows.push(React.createElement(FloatingWindow_1.FloatingWindow, { key: child.getId(), url: this.popoutURL, rect: rect, title: child.getName(), id: child.getId(), onSetWindow: this.onSetWindow, onCloseWindow: this.onCloseWindow },
                        React.createElement(FloatingWindowTab_1.FloatingWindowTab, { layout: this, node: child, factory: this.props.factory })));
                    tabComponents[child.getId()] = React.createElement(TabFloating_1.TabFloating, { key: child.getId(), layout: this, path: newPath, node: child, selected: child === selectedTab });
                }
                else {
                    tabComponents[child.getId()] = React.createElement(Tab_1.Tab, { key: child.getId(), layout: this, path: newPath, node: child, selected: child === selectedTab, factory: this.props.factory });
                }
            }
            else {
                // is row
                const newPath = path + ((child.getOrientation() === Orientation_1.Orientation.HORZ) ? "/r" : "/c") + (rowCount++);
                this.renderChildren(newPath, child, tabSetComponents, tabComponents, floatingWindows, splitterComponents);
            }
        }
    }
    /** @internal */
    _getScreenRect(node) {
        var _a;
        const rect = node.getRect().clone();
        const bodyRect = (_a = this.selfRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
        if (!bodyRect) {
            return null;
        }
        const navHeight = Math.min(80, this.currentWindow.outerHeight - this.currentWindow.innerHeight);
        const navWidth = Math.min(80, this.currentWindow.outerWidth - this.currentWindow.innerWidth);
        rect.x = rect.x + bodyRect.x + this.currentWindow.screenX + navWidth;
        rect.y = rect.y + bodyRect.y + this.currentWindow.screenY + navHeight;
        return rect;
    }
    /**
     * Adds a new tab to the given tabset
     * @param tabsetId the id of the tabset where the new tab will be added
     * @param json the json for the new tab node
     * @returns the added tab node or undefined
     */
    addTabToTabSet(tabsetId, json) {
        const tabsetNode = this.props.model.getNodeById(tabsetId);
        if (tabsetNode !== undefined) {
            const node = this.doAction(Actions_1.Actions.addNode(json, tabsetId, DockLocation_1.DockLocation.CENTER, -1));
            return node;
        }
        return undefined;
    }
    /**
     * Adds a new tab to the active tabset (if there is one)
     * @param json the json for the new tab node
     * @returns the added tab node or undefined
     */
    addTabToActiveTabSet(json) {
        const tabsetNode = this.props.model.getActiveTabset();
        if (tabsetNode !== undefined) {
            const node = this.doAction(Actions_1.Actions.addNode(json, tabsetNode.getId(), DockLocation_1.DockLocation.CENTER, -1));
            return node;
        }
        return undefined;
    }
    /**
     * Adds a new tab by dragging a labeled panel to the drop location, dragging starts immediatelly
     * @param dragText the text to show on the drag panel
     * @param json the json for the new tab node
     * @param onDrop a callback to call when the drag is complete (node and event will be undefined if the drag was cancelled)
     */
    addTabWithDragAndDrop(dragText, json, onDrop) {
        this.fnNewNodeDropped = onDrop;
        this.newTabJson = json;
        this.dragStart(undefined, dragText, TabNode_1.TabNode._fromJson(json, this.props.model, false), true, undefined, undefined);
    }
    /**
     * Move a tab/tabset using drag and drop
     * @param node the tab or tabset to drag
     * @param dragText the text to show on the drag panel
     */
    moveTabWithDragAndDrop(node, dragText) {
        this.dragStart(undefined, dragText, node, true, undefined, undefined);
    }
    /**
     * Adds a new tab by dragging a labeled panel to the drop location, dragging starts when you
     * mouse down on the panel
     *
     * @param dragText the text to show on the drag panel
     * @param json the json for the new tab node
     * @param onDrop a callback to call when the drag is complete (node and event will be undefined if the drag was cancelled)
     */
    addTabWithDragAndDropIndirect(dragText, json, onDrop) {
        this.fnNewNodeDropped = onDrop;
        this.newTabJson = json;
        DragDrop_1.DragDrop.instance.addGlass(this.onCancelAdd);
        this.dragDivText = dragText;
        this.dragDiv = this.currentDocument.createElement("div");
        this.dragDiv.className = this.getClassName(Types_1.CLASSES.FLEXLAYOUT__DRAG_RECT);
        this.dragDiv.addEventListener("mousedown", this.onDragDivMouseDown);
        this.dragDiv.addEventListener("touchstart", this.onDragDivMouseDown, { passive: false });
        this.dragRectRender(this.dragDivText, undefined, this.newTabJson, () => {
            if (this.dragDiv) {
                // now it's been rendered into the dom it can be centered
                this.dragDiv.style.visibility = "visible";
                const domRect = this.dragDiv.getBoundingClientRect();
                const r = new Rect_1.Rect(0, 0, domRect === null || domRect === void 0 ? void 0 : domRect.width, domRect === null || domRect === void 0 ? void 0 : domRect.height);
                r.centerInRect(this.state.rect);
                this.dragDiv.setAttribute("data-layout-path", "/drag-rectangle");
                this.dragDiv.style.left = r.x + "px";
                this.dragDiv.style.top = r.y + "px";
            }
        });
        const rootdiv = this.selfRef.current;
        rootdiv.appendChild(this.dragDiv);
    }
    /** @internal */
    handleCustomTabDrag(dropInfo, pos, event) {
        var _a, _b, _c;
        let invalidated = (_a = this.customDrop) === null || _a === void 0 ? void 0 : _a.invalidated;
        const currentCallback = (_b = this.customDrop) === null || _b === void 0 ? void 0 : _b.callback;
        this.customDrop = undefined;
        const dragging = this.newTabJson || (this.dragNode instanceof TabNode_1.TabNode ? this.dragNode : undefined);
        if (dragging && (dropInfo.node instanceof TabSetNode_1.TabSetNode || dropInfo.node instanceof BorderNode_1.BorderNode) && dropInfo.index === -1) {
            const selected = dropInfo.node.getSelectedNode();
            const tabRect = selected === null || selected === void 0 ? void 0 : selected.getRect();
            if (selected && (tabRect === null || tabRect === void 0 ? void 0 : tabRect.contains(pos.x, pos.y))) {
                let customDrop = undefined;
                try {
                    const dest = this.onTabDrag(dragging, selected, pos.x - tabRect.x, pos.y - tabRect.y, dropInfo.location, () => this.onDragMove(event));
                    if (dest) {
                        customDrop = {
                            rect: new Rect_1.Rect(dest.x + tabRect.x, dest.y + tabRect.y, dest.width, dest.height),
                            callback: dest.callback,
                            invalidated: dest.invalidated,
                            dragging: dragging,
                            over: selected,
                            x: pos.x - tabRect.x,
                            y: pos.y - tabRect.y,
                            location: dropInfo.location,
                            cursor: dest.cursor
                        };
                    }
                }
                catch (e) {
                    console.error(e);
                }
                if ((customDrop === null || customDrop === void 0 ? void 0 : customDrop.callback) === currentCallback) {
                    invalidated = undefined;
                }
                this.customDrop = customDrop;
            }
        }
        this.dropInfo = dropInfo;
        if (this.outlineDiv) {
            this.outlineDiv.className = this.getClassName(this.customDrop ? Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT : dropInfo.className);
            if (this.customDrop) {
                this.customDrop.rect.positionElement(this.outlineDiv);
            }
            else {
                dropInfo.rect.positionElement(this.outlineDiv);
            }
        }
        DragDrop_1.DragDrop.instance.setGlassCursorOverride((_c = this.customDrop) === null || _c === void 0 ? void 0 : _c.cursor);
        if (this.outlineDiv) {
            this.outlineDiv.style.visibility = "visible";
        }
        try {
            invalidated === null || invalidated === void 0 ? void 0 : invalidated();
        }
        catch (e) {
            console.error(e);
        }
    }
    /** @internal */
    onDragEnter(event) {
        // DragDrop keeps track of number of dragenters minus the number of
        // dragleaves. Only start a new drag if there isn't one already.
        if (DragDrop_1.DragDrop.instance.isDragging())
            return;
        const drag = this.props.onExternalDrag(event);
        if (drag) {
            // Mimic addTabWithDragAndDrop, but pass in DragEvent
            this.fnNewNodeDropped = drag.onDrop;
            this.newTabJson = drag.json;
            this.dragStart(event, drag.dragText, TabNode_1.TabNode._fromJson(drag.json, this.props.model, false), true, undefined, undefined);
        }
    }
    /** @internal */
    checkForBorderToShow(x, y) {
        const r = this.props.model._getOuterInnerRects().outer;
        const c = r.getCenter();
        const margin = this.edgeRectWidth;
        const offset = this.edgeRectLength / 2;
        let overEdge = false;
        if (this.props.model.isEnableEdgeDock() && this.state.showHiddenBorder === DockLocation_1.DockLocation.CENTER) {
            if ((y > c.y - offset && y < c.y + offset) ||
                (x > c.x - offset && x < c.x + offset)) {
                overEdge = true;
            }
        }
        let location = DockLocation_1.DockLocation.CENTER;
        if (!overEdge) {
            if (x <= r.x + margin) {
                location = DockLocation_1.DockLocation.LEFT;
            }
            else if (x >= r.getRight() - margin) {
                location = DockLocation_1.DockLocation.RIGHT;
            }
            else if (y <= r.y + margin) {
                location = DockLocation_1.DockLocation.TOP;
            }
            else if (y >= r.getBottom() - margin) {
                location = DockLocation_1.DockLocation.BOTTOM;
            }
        }
        if (location !== this.state.showHiddenBorder) {
            this.setState({ showHiddenBorder: location });
        }
    }
    /** @internal */
    maximize(tabsetNode) {
        this.doAction(Actions_1.Actions.maximizeToggle(tabsetNode.getId()));
    }
    /** @internal */
    customizeTab(tabNode, renderValues) {
        if (this.props.onRenderTab) {
            this.props.onRenderTab(tabNode, renderValues);
        }
    }
    /** @internal */
    customizeTabSet(tabSetNode, renderValues) {
        if (this.props.onRenderTabSet) {
            this.props.onRenderTabSet(tabSetNode, renderValues);
        }
    }
    /** @internal */
    i18nName(id, param) {
        let message;
        if (this.props.i18nMapper) {
            message = this.props.i18nMapper(id, param);
        }
        if (message === undefined) {
            message = id + (param === undefined ? "" : param);
        }
        return message;
    }
    /** @internal */
    getOnRenderFloatingTabPlaceholder() {
        return this.props.onRenderFloatingTabPlaceholder;
    }
    /** @internal */
    getShowOverflowMenu() {
        return this.props.onShowOverflowMenu;
    }
    /** @internal */
    getTabSetPlaceHolderCallback() {
        return this.props.onTabSetPlaceHolder;
    }
    /** @internal */
    showContextMenu(node, event) {
        if (this.props.onContextMenu) {
            this.props.onContextMenu(node, event);
        }
    }
    /** @internal */
    auxMouseClick(node, event) {
        if (this.props.onAuxMouseClick) {
            this.props.onAuxMouseClick(node, event);
        }
    }
}
exports.Layout = Layout;
/** @internal */
const DragRectRenderWrapper = (props) => {
    React.useEffect(() => {
        var _a;
        (_a = props.onRendered) === null || _a === void 0 ? void 0 : _a.call(props);
    }, [props]);
    return (React.createElement(React.Fragment, null, props.children));
};
//# sourceMappingURL=Layout.js.map

/***/ }),

/***/ 7463:
/***/ (function(__unused_webpack_module, exports) {

"use strict";
/**
 * @license React
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,w=e>>>1;d<w;){var m=2*(d+1)-1,C=a[m],n=m+1,x=a[n];if(0>g(C,c))n<e&&0>g(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(n<e&&0>g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}
function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null;
"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}
function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;
function M(){return exports.unstable_now()-Q<P?!1:!0}function R(){if(null!==O){var a=exports.unstable_now();Q=a;var b=!0;try{b=O(!0,a)}finally{b?S():(N=!1,O=null)}}else N=!1}var S;if("function"===typeof F)S=function(){F(R)};else if("undefined"!==typeof MessageChannel){var T=new MessageChannel,U=T.port2;T.port1.onmessage=R;S=function(){U.postMessage(null)}}else S=function(){D(R,0)};function I(a){O=a;N||(N=!0,S())}function K(a,b){L=D(function(){a(exports.unstable_now())},b)}
exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){A||z||(A=!0,I(J))};
exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):P=0<a?Math.floor(1E3/a):5};exports.unstable_getCurrentPriorityLevel=function(){return y};exports.unstable_getFirstCallbackNode=function(){return h(r)};exports.unstable_next=function(a){switch(y){case 1:case 2:case 3:var b=3;break;default:b=y}var c=y;y=b;try{return a()}finally{y=c}};exports.unstable_pauseExecution=function(){};
exports.unstable_requestPaint=function(){};exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=y;y=a;try{return b()}finally{y=c}};
exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:u++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};
exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};


/***/ }),

/***/ 7503:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory(__webpack_require__(6842));
	else // removed by dead control flow
{}
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __nested_webpack_require_633__(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_633__);
/******/
/******/ 		// 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_633__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__nested_webpack_require_633__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__nested_webpack_require_633__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__nested_webpack_require_633__.d = function(exports, name, getter) {
/******/ 		if(!__nested_webpack_require_633__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__nested_webpack_require_633__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__nested_webpack_require_633__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__nested_webpack_require_633__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__nested_webpack_require_633__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __nested_webpack_require_633__(__nested_webpack_require_633__.s = 3);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __nested_webpack_require_3072__) {

"use strict";


var klay = __nested_webpack_require_3072__(4);
var assign = __nested_webpack_require_3072__(1);
var defaults = __nested_webpack_require_3072__(2);

var klayNSLookup = {
  'addUnnecessaryBendpoints': 'de.cau.cs.kieler.klay.layered.unnecessaryBendpoints',
  'alignment': 'de.cau.cs.kieler.alignment',
  'aspectRatio': 'de.cau.cs.kieler.aspectRatio',
  'borderSpacing': 'borderSpacing',
  'compactComponents': 'de.cau.cs.kieler.klay.layered.components.compact',
  'compactionStrategy': 'de.cau.cs.kieler.klay.layered.nodeplace.compactionStrategy',
  'contentAlignment': 'de.cau.cs.kieler.klay.layered.contentAlignment',
  'crossingMinimization': 'de.cau.cs.kieler.klay.layered.crossMin',
  'cycleBreaking': 'de.cau.cs.kieler.klay.layered.cycleBreaking',
  'debugMode': 'de.cau.cs.kieler.debugMode',
  'direction': 'de.cau.cs.kieler.direction',
  'edgeLabelSideSelection': 'de.cau.cs.kieler.klay.layered.edgeLabelSideSelection',
  // <broken> 'de.cau.cs.kieler.klay.layered.edgeNodeSpacingFactor': options.edgeNodeSpacingFactor,
  'edgeRouting': 'de.cau.cs.kieler.edgeRouting',
  'edgeSpacingFactor': 'de.cau.cs.kieler.klay.layered.edgeSpacingFactor',
  'feedbackEdges': 'de.cau.cs.kieler.klay.layered.feedBackEdges',
  'fixedAlignment': 'de.cau.cs.kieler.klay.layered.fixedAlignment',
  'greedySwitchCrossingMinimization': 'de.cau.cs.kieler.klay.layered.greedySwitch',
  'hierarchyHandling': 'de.cau.cs.kieler.hierarchyHandling',
  'inLayerSpacingFactor': 'de.cau.cs.kieler.klay.layered.inLayerSpacingFactor',
  'interactiveReferencePoint': 'de.cau.cs.kieler.klay.layered.interactiveReferencePoint',
  'layerConstraint': 'de.cau.cs.kieler.klay.layered.layerConstraint',
  'layoutHierarchy': 'de.cau.cs.kieler.layoutHierarchy',
  'linearSegmentsDeflectionDampening': 'de.cau.cs.kieler.klay.layered.linearSegmentsDeflectionDampening',
  'mergeEdges': 'de.cau.cs.kieler.klay.layered.mergeEdges',
  'mergeHierarchyCrossingEdges': 'de.cau.cs.kieler.klay.layered.mergeHierarchyEdges',
  'noLayout': 'de.cau.cs.kieler.noLayout',
  'nodeLabelPlacement': 'de.cau.cs.kieler.nodeLabelPlacement',
  'nodeLayering': 'de.cau.cs.kieler.klay.layered.nodeLayering',
  'nodePlacement': 'de.cau.cs.kieler.klay.layered.nodePlace',
  'portAlignment': 'de.cau.cs.kieler.portAlignment',
  'portAlignmentEastern': 'de.cau.cs.kieler.portAlignment.east',
  'portAlignmentNorth': 'de.cau.cs.kieler.portAlignment.north',
  'portAlignmentSouth': 'de.cau.cs.kieler.portAlignment.south',
  'portAlignmentWest': 'de.cau.cs.kieler.portAlignment.west',
  'portConstraints': 'de.cau.cs.kieler.portConstraints',
  'portLabelPlacement': 'de.cau.cs.kieler.portLabelPlacement',
  'portOffset': 'de.cau.cs.kieler.offset',
  'portSide': 'de.cau.cs.kieler.portSide',
  'portSpacing': 'de.cau.cs.kieler.portSpacing',
  'postCompaction': 'de.cau.cs.kieler.klay.layered.postCompaction',
  'priority': 'de.cau.cs.kieler.priority',
  'randomizationSeed': 'de.cau.cs.kieler.randomSeed',
  'routeSelfLoopInside': 'de.cau.cs.kieler.selfLoopInside',
  'separateConnectedComponents': 'de.cau.cs.kieler.separateConnComp',
  'sizeConstraint': 'de.cau.cs.kieler.sizeConstraint',
  'sizeOptions': 'de.cau.cs.kieler.sizeOptions',
  'spacing': 'de.cau.cs.kieler.spacing',
  'splineSelfLoopPlacement': 'de.cau.cs.kieler.klay.layered.splines.selfLoopPlacement',
  'thoroughness': 'de.cau.cs.kieler.klay.layered.thoroughness',
  'wideNodesOnMultipleLayers': 'de.cau.cs.kieler.klay.layered.wideNodesOnMultipleLayers'
};

var mapToKlayNS = function mapToKlayNS(klayOpts) {
  var keys = Object.keys(klayOpts);
  var ret = {};

  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var nsKey = klayNSLookup[key];
    var val = klayOpts[key];

    ret[nsKey] = val;
  }

  return ret;
};

var klayOverrides = {
  interactiveReferencePoint: 'CENTER' // Determines which point of a node is considered by interactive layout phases.
};

var getPos = function getPos(ele) {
  var parent = ele.parent();
  var k = ele.scratch('klay');
  var p = {
    x: k.x,
    y: k.y
  };

  while (parent.nonempty()) {
    var kp = parent.scratch('klay');
    p.x += kp.x;
    p.y += kp.y;
    parent = parent.parent();
  }

  return p;
};

var makeNode = function makeNode(node, options) {
  var dims = node.layoutDimensions(options);
  var padding = node.numericStyle('padding');

  var k = {
    _cyEle: node,
    id: node.id(),
    padding: {
      top: padding,
      left: padding,
      bottom: padding,
      right: padding
    }
  };

  if (!node.isParent()) {
    k.width = dims.w;
    k.height = dims.h;
  }

  node.scratch('klay', k);

  return k;
};

var makeEdge = function makeEdge(edge, options) {
  var k = {
    _cyEle: edge,
    id: edge.id(),
    source: edge.data('source'),
    target: edge.data('target'),
    properties: {}
  };

  var priority = options.priority(edge);

  if (priority != null) {
    k.properties.priority = priority;
  }

  edge.scratch('klay', k);

  return k;
};

var makeGraph = function makeGraph(nodes, edges, options) {
  var klayNodes = [];
  var klayEdges = [];
  var klayEleLookup = {};
  var graph = {
    id: 'root',
    children: [],
    edges: []
  };

  // map all nodes
  for (var i = 0; i < nodes.length; i++) {
    var n = nodes[i];
    var k = makeNode(n, options);

    klayNodes.push(k);

    klayEleLookup[n.id()] = k;
  }

  // map all edges
  for (var _i = 0; _i < edges.length; _i++) {
    var e = edges[_i];
    var _k = makeEdge(e, options);

    klayEdges.push(_k);

    klayEleLookup[e.id()] = _k;
  }

  // make hierarchy
  for (var _i2 = 0; _i2 < klayNodes.length; _i2++) {
    var _k2 = klayNodes[_i2];
    var _n = _k2._cyEle;

    if (!_n.isChild()) {
      graph.children.push(_k2);
    } else {
      var parent = _n.parent();
      var parentK = klayEleLookup[parent.id()];

      var children = parentK.children = parentK.children || [];

      children.push(_k2);
    }
  }

  for (var _i3 = 0; _i3 < klayEdges.length; _i3++) {
    var _k3 = klayEdges[_i3];
    var _e = _k3._cyEle;
    var parentSrc = _e.source().parent();
    var parentTgt = _e.target().parent();

    // put all edges in the top level for now
    // TODO does this cause issues in certain edgecases?
    if (false) // removed by dead control flow
{ var kp; } else {
      graph.edges.push(_k3);
    }
  }

  return graph;
};

function Layout(options) {
  var klayOptions = options.klay;

  this.options = assign({}, defaults, options);

  this.options.klay = assign({}, defaults.klay, klayOptions, klayOverrides);
}

Layout.prototype.run = function () {
  var layout = this;
  var options = this.options;

  var eles = options.eles;
  var nodes = eles.nodes();
  var edges = eles.edges();

  var graph = makeGraph(nodes, edges, options);

  klay.layout({
    graph: graph,
    options: mapToKlayNS(options.klay),
    success: function success() {},
    error: function error(_error) {
      throw _error;
    }
  });

  nodes.filter(function (n) {
    return !n.isParent();
  }).layoutPositions(layout, options, getPos);

  return this;
};

Layout.prototype.stop = function () {
  return this; // chaining
};

Layout.prototype.destroy = function () {
  return this; // chaining
};

module.exports = Layout;

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// Simple, internal Object.assign() polyfill for options objects etc.

module.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
  for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    srcs[_key - 1] = arguments[_key];
  }

  srcs.filter(function (src) {
    return src != null;
  }).forEach(function (src) {
    Object.keys(src).forEach(function (k) {
      return tgt[k] = src[k];
    });
  });

  return tgt;
};

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var defaults = {
  nodeDimensionsIncludeLabels: false, // Boolean which changes whether label dimensions are included when calculating node dimensions
  fit: true, // Whether to fit
  padding: 20, // Padding on fit
  animate: false, // Whether to transition the node positions
  animateFilter: function animateFilter(node, i) {
    return true;
  }, // Whether to animate specific nodes when animation is on; non-animated nodes immediately go to their final positions
  animationDuration: 500, // Duration of animation in ms if enabled
  animationEasing: undefined, // Easing of animation if enabled
  transform: function transform(node, pos) {
    return pos;
  }, // A function that applies a transform to the final node position
  ready: undefined, // Callback on layoutready
  stop: undefined, // Callback on layoutstop
  klay: {
    // Following descriptions taken from http://layout.rtsys.informatik.uni-kiel.de:9444/Providedlayout.html?algorithm=de.cau.cs.kieler.klay.layered
    addUnnecessaryBendpoints: false, // Adds bend points even if an edge does not change direction.
    aspectRatio: 1.6, // The aimed aspect ratio of the drawing, that is the quotient of width by height
    borderSpacing: 20, // Minimal amount of space to be left to the border
    compactComponents: false, // Tries to further compact components (disconnected sub-graphs).
    crossingMinimization: 'LAYER_SWEEP', // Strategy for crossing minimization.
    /* LAYER_SWEEP The layer sweep algorithm iterates multiple times over the layers, trying to find node orderings that minimize the number of crossings. The algorithm uses randomization to increase the odds of finding a good result. To improve its results, consider increasing the Thoroughness option, which influences the number of iterations done. The Randomization seed also influences results.
    INTERACTIVE Orders the nodes of each layer by comparing their positions before the layout algorithm was started. The idea is that the relative order of nodes as it was before layout was applied is not changed. This of course requires valid positions for all nodes to have been set on the input graph before calling the layout algorithm. The interactive layer sweep algorithm uses the Interactive Reference Point option to determine which reference point of nodes are used to compare positions. */
    cycleBreaking: 'GREEDY', // Strategy for cycle breaking. Cycle breaking looks for cycles in the graph and determines which edges to reverse to break the cycles. Reversed edges will end up pointing to the opposite direction of regular edges (that is, reversed edges will point left if edges usually point right).
    /* GREEDY This algorithm reverses edges greedily. The algorithm tries to avoid edges that have the Priority property set.
    INTERACTIVE The interactive algorithm tries to reverse edges that already pointed leftwards in the input graph. This requires node and port coordinates to have been set to sensible values.*/
    direction: 'UNDEFINED', // Overall direction of edges: horizontal (right / left) or vertical (down / up)
    /* UNDEFINED, RIGHT, LEFT, DOWN, UP */
    edgeRouting: 'ORTHOGONAL', // Defines how edges are routed (POLYLINE, ORTHOGONAL, SPLINES)
    edgeSpacingFactor: 0.5, // Factor by which the object spacing is multiplied to arrive at the minimal spacing between edges.
    feedbackEdges: false, // Whether feedback edges should be highlighted by routing around the nodes.
    fixedAlignment: 'NONE', // Tells the BK node placer to use a certain alignment instead of taking the optimal result.  This option should usually be left alone.
    /* NONE Chooses the smallest layout from the four possible candidates.
    LEFTUP Chooses the left-up candidate from the four possible candidates.
    RIGHTUP Chooses the right-up candidate from the four possible candidates.
    LEFTDOWN Chooses the left-down candidate from the four possible candidates.
    RIGHTDOWN Chooses the right-down candidate from the four possible candidates.
    BALANCED Creates a balanced layout from the four possible candidates. */
    inLayerSpacingFactor: 1.0, // Factor by which the usual spacing is multiplied to determine the in-layer spacing between objects.
    layoutHierarchy: false, // Whether the selected layouter should consider the full hierarchy
    linearSegmentsDeflectionDampening: 0.3, // Dampens the movement of nodes to keep the diagram from getting too large.
    mergeEdges: false, // Edges that have no ports are merged so they touch the connected nodes at the same points.
    mergeHierarchyCrossingEdges: true, // If hierarchical layout is active, hierarchy-crossing edges use as few hierarchical ports as possible.
    nodeLayering: 'NETWORK_SIMPLEX', // Strategy for node layering.
    /* NETWORK_SIMPLEX This algorithm tries to minimize the length of edges. This is the most computationally intensive algorithm. The number of iterations after which it aborts if it hasn't found a result yet can be set with the Maximal Iterations option.
    LONGEST_PATH A very simple algorithm that distributes nodes along their longest path to a sink node.
    INTERACTIVE Distributes the nodes into layers by comparing their positions before the layout algorithm was started. The idea is that the relative horizontal order of nodes as it was before layout was applied is not changed. This of course requires valid positions for all nodes to have been set on the input graph before calling the layout algorithm. The interactive node layering algorithm uses the Interactive Reference Point option to determine which reference point of nodes are used to compare positions. */
    nodePlacement: 'BRANDES_KOEPF', // Strategy for Node Placement
    /* BRANDES_KOEPF Minimizes the number of edge bends at the expense of diagram size: diagrams drawn with this algorithm are usually higher than diagrams drawn with other algorithms.
    LINEAR_SEGMENTS Computes a balanced placement.
    INTERACTIVE Tries to keep the preset y coordinates of nodes from the original layout. For dummy nodes, a guess is made to infer their coordinates. Requires the other interactive phase implementations to have run as well.
    SIMPLE Minimizes the area at the expense of... well, pretty much everything else. */
    randomizationSeed: 1, // Seed used for pseudo-random number generators to control the layout algorithm; 0 means a new seed is generated
    routeSelfLoopInside: false, // Whether a self-loop is routed around or inside its node.
    separateConnectedComponents: true, // Whether each connected component should be processed separately
    spacing: 20, // Overall setting for the minimal amount of space to be left between objects
    thoroughness: 7 // How much effort should be spent to produce a nice layout..
  },
  priority: function priority(edge) {
    return null;
  } // Edges with a non-nil value are skipped when geedy edge cycle breaking is enabled
};

module.exports = defaults;

/***/ }),
/* 3 */
/***/ (function(module, exports, __nested_webpack_require_18023__) {

"use strict";


var impl = __nested_webpack_require_18023__(0);

// registers the extension on a cytoscape lib ref
var register = function register(cytoscape) {
  if (!cytoscape) {
    return;
  } // can't register if cytoscape unspecified

  cytoscape('layout', 'klay', impl); // register with cytoscape.js
};

if (typeof cytoscape !== 'undefined') {
  // expose to global cytoscape (i.e. window.cytoscape)
  register(cytoscape);
}

module.exports = register;

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_4__;

/***/ })
/******/ ]);
});

/***/ }),

/***/ 7515:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FloatingWindowTab = void 0;
const React = __webpack_require__(6540);
const ErrorBoundary_1 = __webpack_require__(6834);
const I18nLabel_1 = __webpack_require__(300);
const react_1 = __webpack_require__(6540);
const Types_1 = __webpack_require__(6643);
/** @internal */
const FloatingWindowTab = (props) => {
    const { layout, node, factory } = props;
    const cm = layout.getClassName;
    const child = factory(node);
    return (React.createElement("div", { className: cm(Types_1.CLASSES.FLEXLAYOUT__FLOATING_WINDOW_TAB) },
        React.createElement(ErrorBoundary_1.ErrorBoundary, { message: props.layout.i18nName(I18nLabel_1.I18nLabel.Error_rendering_component) },
            React.createElement(react_1.Fragment, null, child))));
};
exports.FloatingWindowTab = FloatingWindowTab;
//# sourceMappingURL=FloatingWindowTab.js.map

/***/ }),

/***/ 7618:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Node = void 0;
const DockLocation_1 = __webpack_require__(8324);
const Orientation_1 = __webpack_require__(1648);
const Rect_1 = __webpack_require__(2530);
class Node {
    /** @internal */
    constructor(model) {
        /** @internal */
        this._dirty = false;
        /** @internal */
        this._tempSize = 0;
        this._model = model;
        this._attributes = {};
        this._children = [];
        this._fixed = false;
        this._rect = Rect_1.Rect.empty();
        this._visible = false;
        this._listeners = {};
    }
    getId() {
        let id = this._attributes.id;
        if (id !== undefined) {
            return id;
        }
        id = this._model._nextUniqueId();
        this._setId(id);
        return id;
    }
    getModel() {
        return this._model;
    }
    getType() {
        return this._attributes.type;
    }
    getParent() {
        return this._parent;
    }
    getChildren() {
        return this._children;
    }
    getRect() {
        return this._rect;
    }
    isVisible() {
        return this._visible;
    }
    getOrientation() {
        if (this._parent === undefined) {
            return this._model.isRootOrientationVertical() ? Orientation_1.Orientation.VERT : Orientation_1.Orientation.HORZ;
        }
        else {
            return Orientation_1.Orientation.flip(this._parent.getOrientation());
        }
    }
    // event can be: resize, visibility, maximize (on tabset), close
    setEventListener(event, callback) {
        this._listeners[event] = callback;
    }
    removeEventListener(event) {
        delete this._listeners[event];
    }
    /** @internal */
    _setId(id) {
        this._attributes.id = id;
    }
    /** @internal */
    _fireEvent(event, params) {
        // console.log(this._type, " fireEvent " + event + " " + JSON.stringify(params));
        if (this._listeners[event] !== undefined) {
            this._listeners[event](params);
        }
    }
    /** @internal */
    _getAttr(name) {
        let val = this._attributes[name];
        if (val === undefined) {
            const modelName = this._getAttributeDefinitions().getModelName(name);
            if (modelName !== undefined) {
                val = this._model._getAttribute(modelName);
            }
        }
        // console.log(name + "=" + val);
        return val;
    }
    /** @internal */
    _forEachNode(fn, level) {
        fn(this, level);
        level++;
        for (const node of this._children) {
            node._forEachNode(fn, level);
        }
    }
    /** @internal */
    _setVisible(visible) {
        if (visible !== this._visible) {
            this._fireEvent("visibility", { visible });
            this._visible = visible;
        }
    }
    /** @internal */
    _getDrawChildren() {
        return this._children;
    }
    /** @internal */
    _setParent(parent) {
        this._parent = parent;
    }
    /** @internal */
    _setRect(rect) {
        this._rect = rect;
    }
    /** @internal */
    _setWeight(weight) {
        this._attributes.weight = weight;
    }
    /** @internal */
    _setSelected(index) {
        this._attributes.selected = index;
    }
    /** @internal */
    _isFixed() {
        return this._fixed;
    }
    /** @internal */
    _layout(rect, metrics) {
        this._rect = rect;
    }
    /** @internal */
    _findDropTargetNode(dragNode, x, y) {
        let rtn;
        if (this._rect.contains(x, y)) {
            if (this._model.getMaximizedTabset() !== undefined) {
                rtn = this._model.getMaximizedTabset().canDrop(dragNode, x, y);
            }
            else {
                rtn = this.canDrop(dragNode, x, y);
                if (rtn === undefined) {
                    if (this._children.length !== 0) {
                        for (const child of this._children) {
                            rtn = child._findDropTargetNode(dragNode, x, y);
                            if (rtn !== undefined) {
                                break;
                            }
                        }
                    }
                }
            }
        }
        return rtn;
    }
    /** @internal */
    canDrop(dragNode, x, y) {
        return undefined;
    }
    /** @internal */
    _canDockInto(dragNode, dropInfo) {
        if (dropInfo != null) {
            if (dropInfo.location === DockLocation_1.DockLocation.CENTER && dropInfo.node.isEnableDrop() === false) {
                return false;
            }
            // prevent named tabset docking into another tabset, since this would lose the header
            if (dropInfo.location === DockLocation_1.DockLocation.CENTER && dragNode.getType() === "tabset" && dragNode.getName() !== undefined) {
                return false;
            }
            if (dropInfo.location !== DockLocation_1.DockLocation.CENTER && dropInfo.node.isEnableDivide() === false) {
                return false;
            }
            // finally check model callback to check if drop allowed
            if (this._model._getOnAllowDrop()) {
                return this._model._getOnAllowDrop()(dragNode, dropInfo);
            }
        }
        return true;
    }
    /** @internal */
    _removeChild(childNode) {
        const pos = this._children.indexOf(childNode);
        if (pos !== -1) {
            this._children.splice(pos, 1);
        }
        this._dirty = true;
        return pos;
    }
    /** @internal */
    _addChild(childNode, pos) {
        if (pos != null) {
            this._children.splice(pos, 0, childNode);
        }
        else {
            this._children.push(childNode);
            pos = this._children.length - 1;
        }
        childNode._parent = this;
        this._dirty = true;
        return pos;
    }
    /** @internal */
    _removeAll() {
        this._children = [];
        this._dirty = true;
    }
    /** @internal */
    _styleWithPosition(style) {
        if (style == null) {
            style = {};
        }
        return this._rect.styleWithPosition(style);
    }
    /** @internal */
    _getTempSize() {
        return this._tempSize;
    }
    /** @internal */
    _setTempSize(value) {
        this._tempSize = value;
    }
    /** @internal */
    isEnableDivide() {
        return true;
    }
    /** @internal */
    _toAttributeString() {
        return JSON.stringify(this._attributes, undefined, "\t");
    }
}
exports.Node = Node;
//# sourceMappingURL=Node.js.map

/***/ }),

/***/ 7767:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

"use strict";
var react__WEBPACK_IMPORTED_MODULE_0___namespace_cache;
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   BV: function() { return /* binding */ Routes; },
/* harmony export */   C5: function() { return /* binding */ Navigate; },
/* harmony export */   Ix: function() { return /* binding */ Router; },
/* harmony export */   Zp: function() { return /* binding */ useNavigate; },
/* harmony export */   qh: function() { return /* binding */ Route; }
/* harmony export */ });
/* unused harmony exports Await, MemoryRouter, Outlet, RouterProvider, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_mapRouteProperties, UNSAFE_useRouteId, UNSAFE_useRoutesImpl, createMemoryRouter, createRoutesFromChildren, createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6540);
/* harmony import */ var _remix_run_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5588);
/**
 * React Router v6.22.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */




function _extends() {
  _extends = Object.assign ? Object.assign.bind() : 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);
}

// Create react-specific types from the agnostic types in @remix-run/router to
// export from react-router
const DataRouterContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
if (false) // removed by dead control flow
{}
const DataRouterStateContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
if (false) // removed by dead control flow
{}
const AwaitContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
if (false) // removed by dead control flow
{}

/**
 * A Navigator is a "location changer"; it's how you get to different locations.
 *
 * Every history instance conforms to the Navigator interface, but the
 * distinction is useful primarily when it comes to the low-level `<Router>` API
 * where both the location and a navigator must be provided separately in order
 * to avoid "tearing" that may occur in a suspense-enabled app if the action
 * and/or location were to be read directly from the history instance.
 */

const NavigationContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
if (false) // removed by dead control flow
{}
const LocationContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
if (false) // removed by dead control flow
{}
const RouteContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext({
  outlet: null,
  matches: [],
  isDataRoute: false
});
if (false) // removed by dead control flow
{}
const RouteErrorContext = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
if (false) // removed by dead control flow
{}

/**
 * Returns the full href for the given "to" value. This is useful for building
 * custom links that are also accessible and preserve right-click behavior.
 *
 * @see https://reactrouter.com/hooks/use-href
 */
function useHref(to, _temp) {
  let {
    relative
  } = _temp === void 0 ? {} : _temp;
  !useInRouterContext() ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  let {
    basename,
    navigator
  } = React.useContext(NavigationContext);
  let {
    hash,
    pathname,
    search
  } = useResolvedPath(to, {
    relative
  });
  let joinedPathname = pathname;

  // If we're operating within a basename, prepend it to the pathname prior
  // to creating the href.  If this is a root navigation, then just use the raw
  // basename which allows the basename to have full control over the presence
  // of a trailing slash on root links
  if (basename !== "/") {
    joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  }
  return navigator.createHref({
    pathname: joinedPathname,
    search,
    hash
  });
}

/**
 * Returns true if this component is a descendant of a `<Router>`.
 *
 * @see https://reactrouter.com/hooks/use-in-router-context
 */
function useInRouterContext() {
  return react__WEBPACK_IMPORTED_MODULE_0__.useContext(LocationContext) != null;
}

/**
 * Returns the current location object, which represents the current URL in web
 * browsers.
 *
 * Note: If you're using this it may mean you're doing some of your own
 * "routing" in your app, and we'd like to know what your use case is. We may
 * be able to provide something higher-level to better suit your needs.
 *
 * @see https://reactrouter.com/hooks/use-location
 */
function useLocation() {
  !useInRouterContext() ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  return react__WEBPACK_IMPORTED_MODULE_0__.useContext(LocationContext).location;
}

/**
 * Returns the current navigation action which describes how the router came to
 * the current location, either by a pop, push, or replace on the history stack.
 *
 * @see https://reactrouter.com/hooks/use-navigation-type
 */
function useNavigationType() {
  return React.useContext(LocationContext).navigationType;
}

/**
 * Returns a PathMatch object if the given pattern matches the current URL.
 * This is useful for components that need to know "active" state, e.g.
 * `<NavLink>`.
 *
 * @see https://reactrouter.com/hooks/use-match
 */
function useMatch(pattern) {
  !useInRouterContext() ?  false ? 0 : UNSAFE_invariant(false) : void 0;
  let {
    pathname
  } = useLocation();
  return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
}

/**
 * The interface for the navigate() function returned from useNavigate().
 */

const navigateEffectWarning = (/* unused pure expression or super */ null && ("You should call navigate() in a React.useEffect(), not when " + "your component is first rendered."));

// Mute warnings for calls to useNavigate in SSR environments
function useIsomorphicLayoutEffect(cb) {
  let isStatic = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext).static;
  if (!isStatic) {
    // We should be able to get rid of this once react 18.3 is released
    // See: https://github.com/facebook/react/pull/26395
    // eslint-disable-next-line react-hooks/rules-of-hooks
    react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect(cb);
  }
}

/**
 * Returns an imperative method for changing the location. Used by `<Link>`s, but
 * may also be used by other elements to change the location.
 *
 * @see https://reactrouter.com/hooks/use-navigate
 */
function useNavigate() {
  let {
    isDataRoute
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext);
  // Conditional usage is OK here because the usage of a data router is static
  // eslint-disable-next-line react-hooks/rules-of-hooks
  return isDataRoute ? useNavigateStable() : useNavigateUnstable();
}
function useNavigateUnstable() {
  !useInRouterContext() ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  let dataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext);
  let {
    basename,
    future,
    navigator
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext);
  let {
    matches
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify((0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_getResolveToMatches */ .yD)(matches, future.v7_relativeSplatPath));
  let activeRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(false);
  useIsomorphicLayoutEffect(() => {
    activeRef.current = true;
  });
  let navigate = react__WEBPACK_IMPORTED_MODULE_0__.useCallback(function (to, options) {
    if (options === void 0) {
      options = {};
    }
     false ? 0 : void 0;

    // Short circuit here since if this happens on first render the navigate
    // is useless because we haven't wired up our history listener yet
    if (!activeRef.current) return;
    if (typeof to === "number") {
      navigator.go(to);
      return;
    }
    let path = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .resolveTo */ .Gh)(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");

    // If we're operating within a basename, prepend it to the pathname prior
    // to handing off to history (but only if we're not in a data router,
    // otherwise it'll prepend the basename inside of the router).
    // If this is a root navigation, then we navigate to the raw basename
    // which allows the basename to have full control over the presence of a
    // trailing slash on root links
    if (dataRouterContext == null && basename !== "/") {
      path.pathname = path.pathname === "/" ? basename : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .joinPaths */ .HS)([basename, path.pathname]);
    }
    (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
  }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
  return navigate;
}
const OutletContext = /*#__PURE__*/(/* unused pure expression or super */ null && (React.createContext(null)));

/**
 * Returns the context (if provided) for the child route at this level of the route
 * hierarchy.
 * @see https://reactrouter.com/hooks/use-outlet-context
 */
function useOutletContext() {
  return React.useContext(OutletContext);
}

/**
 * Returns the element for the child route at this level of the route
 * hierarchy. Used internally by `<Outlet>` to render child routes.
 *
 * @see https://reactrouter.com/hooks/use-outlet
 */
function useOutlet(context) {
  let outlet = React.useContext(RouteContext).outlet;
  if (outlet) {
    return /*#__PURE__*/React.createElement(OutletContext.Provider, {
      value: context
    }, outlet);
  }
  return outlet;
}

/**
 * Returns an object of key/value pairs of the dynamic params from the current
 * URL that were matched by the route path.
 *
 * @see https://reactrouter.com/hooks/use-params
 */
function useParams() {
  let {
    matches
  } = React.useContext(RouteContext);
  let routeMatch = matches[matches.length - 1];
  return routeMatch ? routeMatch.params : {};
}

/**
 * Resolves the pathname of the given `to` value against the current location.
 *
 * @see https://reactrouter.com/hooks/use-resolved-path
 */
function useResolvedPath(to, _temp2) {
  let {
    relative
  } = _temp2 === void 0 ? {} : _temp2;
  let {
    future
  } = React.useContext(NavigationContext);
  let {
    matches
  } = React.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
}

/**
 * Returns the element of the route that matched the current location, prepared
 * with the correct context to render the remainder of the route tree. Route
 * elements in the tree must render an `<Outlet>` to render their child route's
 * element.
 *
 * @see https://reactrouter.com/hooks/use-routes
 */
function useRoutes(routes, locationArg) {
  return useRoutesImpl(routes, locationArg);
}

// Internal implementation with accept optional param for RouterProvider usage
function useRoutesImpl(routes, locationArg, dataRouterState, future) {
  !useInRouterContext() ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  let {
    navigator
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext);
  let {
    matches: parentMatches
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext);
  let routeMatch = parentMatches[parentMatches.length - 1];
  let parentParams = routeMatch ? routeMatch.params : {};
  let parentPathname = routeMatch ? routeMatch.pathname : "/";
  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  let parentRoute = routeMatch && routeMatch.route;
  if (false) // removed by dead control flow
{}
  let locationFromContext = useLocation();
  let location;
  if (locationArg) {
    var _parsedLocationArg$pa;
    let parsedLocationArg = typeof locationArg === "string" ? (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .parsePath */ .Rr)(locationArg) : locationArg;
    !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
    location = parsedLocationArg;
  } else {
    location = locationFromContext;
  }
  let pathname = location.pathname || "/";
  let remainingPathname = pathname;
  if (parentPathnameBase !== "/") {
    // Determine the remaining pathname by removing the # of URL segments the
    // parentPathnameBase has, instead of removing based on character count.
    // This is because we can't guarantee that incoming/outgoing encodings/
    // decodings will match exactly.
    // We decode paths before matching on a per-segment basis with
    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they
    // match what `window.location.pathname` would reflect.  Those don't 100%
    // align when it comes to encoded URI characters such as % and &.
    //
    // So we may end up with:
    //   pathname:           "/descendant/a%25b/match"
    //   parentPathnameBase: "/descendant/a%b"
    //
    // And the direct substring removal approach won't work :/
    let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
    let segments = pathname.replace(/^\//, "").split("/");
    remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  }
  let matches = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .matchRoutes */ .ue)(routes, {
    pathname: remainingPathname
  });
  if (false) // removed by dead control flow
{}
  let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
    params: Object.assign({}, parentParams, match.params),
    pathname: (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .joinPaths */ .HS)([parentPathnameBase,
    // Re-encode pathnames that were decoded inside matchRoutes
    navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
    pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .joinPaths */ .HS)([parentPathnameBase,
    // Re-encode pathnames that were decoded inside matchRoutes
    navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
  })), parentMatches, dataRouterState, future);

  // When a user passes in a `locationArg`, the associated routes need to
  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
  // to use the scoped location instead of the global location.
  if (locationArg && renderedMatches) {
    return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(LocationContext.Provider, {
      value: {
        location: _extends({
          pathname: "/",
          search: "",
          hash: "",
          state: null,
          key: "default"
        }, location),
        navigationType: _remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .Action */ .rc.Pop
      }
    }, renderedMatches);
  }
  return renderedMatches;
}
function DefaultErrorComponent() {
  let error = useRouteError();
  let message = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .isRouteErrorResponse */ .pX)(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
  let stack = error instanceof Error ? error.stack : null;
  let lightgrey = "rgba(200,200,200, 0.5)";
  let preStyles = {
    padding: "0.5rem",
    backgroundColor: lightgrey
  };
  let codeStyles = {
    padding: "2px 4px",
    backgroundColor: lightgrey
  };
  let devInfo = null;
  if (false) // removed by dead control flow
{}
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("h3", {
    style: {
      fontStyle: "italic"
    }
  }, message), stack ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("pre", {
    style: preStyles
  }, stack) : null, devInfo);
}
const defaultErrorElement = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(DefaultErrorComponent, null);
class RenderErrorBoundary extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: props.location,
      revalidation: props.revalidation,
      error: props.error
    };
  }
  static getDerivedStateFromError(error) {
    return {
      error: error
    };
  }
  static getDerivedStateFromProps(props, state) {
    // When we get into an error state, the user will likely click "back" to the
    // previous page that didn't have an error. Because this wraps the entire
    // application, that will have no effect--the error page continues to display.
    // This gives us a mechanism to recover from the error when the location changes.
    //
    // Whether we're in an error state or not, we update the location in state
    // so that when we are in an error state, it gets reset when a new location
    // comes in and the user recovers from the error.
    if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
      return {
        error: props.error,
        location: props.location,
        revalidation: props.revalidation
      };
    }

    // If we're not changing locations, preserve the location but still surface
    // any new errors that may come through. We retain the existing error, we do
    // this because the error provided from the app state may be cleared without
    // the location changing.
    return {
      error: props.error !== undefined ? props.error : state.error,
      location: state.location,
      revalidation: props.revalidation || state.revalidation
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("React Router caught the following error during render", error, errorInfo);
  }
  render() {
    return this.state.error !== undefined ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(RouteContext.Provider, {
      value: this.props.routeContext
    }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(RouteErrorContext.Provider, {
      value: this.state.error,
      children: this.props.component
    })) : this.props.children;
  }
}
function RenderedRoute(_ref) {
  let {
    routeContext,
    match,
    children
  } = _ref;
  let dataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext);

  // Track how deep we got in our render pass to emulate SSR componentDidCatch
  // in a DataStaticRouter
  if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  }
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(RouteContext.Provider, {
    value: routeContext
  }, children);
}
function _renderMatches(matches, parentMatches, dataRouterState, future) {
  var _dataRouterState2;
  if (parentMatches === void 0) {
    parentMatches = [];
  }
  if (dataRouterState === void 0) {
    dataRouterState = null;
  }
  if (future === void 0) {
    future = null;
  }
  if (matches == null) {
    var _dataRouterState;
    if ((_dataRouterState = dataRouterState) != null && _dataRouterState.errors) {
      // Don't bail if we have data router errors so we can render them in the
      // boundary.  Use the pre-matched (or shimmed) matches
      matches = dataRouterState.matches;
    } else {
      return null;
    }
  }
  let renderedMatches = matches;

  // If we have data errors, trim matches to the highest error boundary
  let errors = (_dataRouterState2 = dataRouterState) == null ? void 0 : _dataRouterState2.errors;
  if (errors != null) {
    let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
    !(errorIndex >= 0) ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
    renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  }

  // If we're in a partial hydration mode, detect if we need to render down to
  // a given HydrateFallback while we load the rest of the hydration data
  let renderFallback = false;
  let fallbackIndex = -1;
  if (dataRouterState && future && future.v7_partialHydration) {
    for (let i = 0; i < renderedMatches.length; i++) {
      let match = renderedMatches[i];
      // Track the deepest fallback up until the first route without data
      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
        fallbackIndex = i;
      }
      if (match.route.id) {
        let {
          loaderData,
          errors
        } = dataRouterState;
        let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);
        if (match.route.lazy || needsToRunLoader) {
          // We found the first route that's not ready to render (waiting on
          // lazy, or has a loader that hasn't run yet).  Flag that we need to
          // render a fallback and render up until the appropriate fallback
          renderFallback = true;
          if (fallbackIndex >= 0) {
            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
          } else {
            renderedMatches = [renderedMatches[0]];
          }
          break;
        }
      }
    }
  }
  return renderedMatches.reduceRight((outlet, match, index) => {
    // Only data routers handle errors/fallbacks
    let error;
    let shouldRenderHydrateFallback = false;
    let errorElement = null;
    let hydrateFallbackElement = null;
    if (dataRouterState) {
      error = errors && match.route.id ? errors[match.route.id] : undefined;
      errorElement = match.route.errorElement || defaultErrorElement;
      if (renderFallback) {
        if (fallbackIndex < 0 && index === 0) {
          warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = null;
        } else if (fallbackIndex === index) {
          shouldRenderHydrateFallback = true;
          hydrateFallbackElement = match.route.hydrateFallbackElement || null;
        }
      }
    }
    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
    let getChildren = () => {
      let children;
      if (error) {
        children = errorElement;
      } else if (shouldRenderHydrateFallback) {
        children = hydrateFallbackElement;
      } else if (match.route.Component) {
        // Note: This is a de-optimized path since React won't re-use the
        // ReactElement since it's identity changes with each new
        // React.createElement call.  We keep this so folks can use
        // `<Route Component={...}>` in `<Routes>` but generally `Component`
        // usage is only advised in `RouterProvider` when we can convert it to
        // `element` ahead of time.
        children = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(match.route.Component, null);
      } else if (match.route.element) {
        children = match.route.element;
      } else {
        children = outlet;
      }
      return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(RenderedRoute, {
        match: match,
        routeContext: {
          outlet,
          matches,
          isDataRoute: dataRouterState != null
        },
        children: children
      });
    };
    // Only wrap in an error boundary within data router usages when we have an
    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to
    // an ancestor ErrorBoundary/errorElement
    return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(RenderErrorBoundary, {
      location: dataRouterState.location,
      revalidation: dataRouterState.revalidation,
      component: errorElement,
      error: error,
      children: getChildren(),
      routeContext: {
        outlet: null,
        matches,
        isDataRoute: true
      }
    }) : getChildren();
  }, null);
}
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
  DataRouterHook["UseBlocker"] = "useBlocker";
  DataRouterHook["UseRevalidator"] = "useRevalidator";
  DataRouterHook["UseNavigateStable"] = "useNavigate";
  return DataRouterHook;
}(DataRouterHook || {});
var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
  DataRouterStateHook["UseBlocker"] = "useBlocker";
  DataRouterStateHook["UseLoaderData"] = "useLoaderData";
  DataRouterStateHook["UseActionData"] = "useActionData";
  DataRouterStateHook["UseRouteError"] = "useRouteError";
  DataRouterStateHook["UseNavigation"] = "useNavigation";
  DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
  DataRouterStateHook["UseMatches"] = "useMatches";
  DataRouterStateHook["UseRevalidator"] = "useRevalidator";
  DataRouterStateHook["UseNavigateStable"] = "useNavigate";
  DataRouterStateHook["UseRouteId"] = "useRouteId";
  return DataRouterStateHook;
}(DataRouterStateHook || {});
function getDataRouterConsoleError(hookName) {
  return hookName + " must be used within a data router.  See https://reactrouter.com/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
  let ctx = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext);
  !ctx ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  return ctx;
}
function useDataRouterState(hookName) {
  let state = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterStateContext);
  !state ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  return state;
}
function useRouteContext(hookName) {
  let route = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext);
  !route ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  return route;
}

// Internal version with hookName-aware debugging
function useCurrentRouteId(hookName) {
  let route = useRouteContext(hookName);
  let thisRoute = route.matches[route.matches.length - 1];
  !thisRoute.route.id ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  return thisRoute.route.id;
}

/**
 * Returns the ID for the nearest contextual route
 */
function useRouteId() {
  return useCurrentRouteId(DataRouterStateHook.UseRouteId);
}

/**
 * Returns the current navigation, defaulting to an "idle" navigation when
 * no navigation is in progress
 */
function useNavigation() {
  let state = useDataRouterState(DataRouterStateHook.UseNavigation);
  return state.navigation;
}

/**
 * Returns a revalidate function for manually triggering revalidation, as well
 * as the current state of any manual revalidations
 */
function useRevalidator() {
  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
  return React.useMemo(() => ({
    revalidate: dataRouterContext.router.revalidate,
    state: state.revalidation
  }), [dataRouterContext.router.revalidate, state.revalidation]);
}

/**
 * Returns the active route matches, useful for accessing loaderData for
 * parent/child routes or the route "handle" property
 */
function useMatches() {
  let {
    matches,
    loaderData
  } = useDataRouterState(DataRouterStateHook.UseMatches);
  return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
}

/**
 * Returns the loader data for the nearest ancestor Route loader
 */
function useLoaderData() {
  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  if (state.errors && state.errors[routeId] != null) {
    console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
    return undefined;
  }
  return state.loaderData[routeId];
}

/**
 * Returns the loaderData for the given routeId
 */
function useRouteLoaderData(routeId) {
  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
  return state.loaderData[routeId];
}

/**
 * Returns the action data for the nearest ancestor Route action
 */
function useActionData() {
  let state = useDataRouterState(DataRouterStateHook.UseActionData);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  return state.actionData ? state.actionData[routeId] : undefined;
}

/**
 * Returns the nearest ancestor Route error, which could be a loader/action
 * error or a render error.  This is intended to be called from your
 * ErrorBoundary/errorElement to display a proper error message.
 */
function useRouteError() {
  var _state$errors;
  let error = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteErrorContext);
  let state = useDataRouterState(DataRouterStateHook.UseRouteError);
  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);

  // If this was a render error, we put it in a RouteError context inside
  // of RenderErrorBoundary
  if (error !== undefined) {
    return error;
  }

  // Otherwise look for errors from our data router state
  return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
}

/**
 * Returns the happy-path data from the nearest ancestor `<Await />` value
 */
function useAsyncValue() {
  let value = React.useContext(AwaitContext);
  return value == null ? void 0 : value._data;
}

/**
 * Returns the error from the nearest ancestor `<Await />` value
 */
function useAsyncError() {
  let value = React.useContext(AwaitContext);
  return value == null ? void 0 : value._error;
}
let blockerId = 0;

/**
 * Allow the application to block navigations within the SPA and present the
 * user a confirmation dialog to confirm the navigation.  Mostly used to avoid
 * using half-filled form data.  This does not handle hard-reloads or
 * cross-origin navigations.
 */
function useBlocker(shouldBlock) {
  let {
    router,
    basename
  } = useDataRouterContext(DataRouterHook.UseBlocker);
  let state = useDataRouterState(DataRouterStateHook.UseBlocker);
  let [blockerKey, setBlockerKey] = React.useState("");
  let blockerFunction = React.useCallback(arg => {
    if (typeof shouldBlock !== "function") {
      return !!shouldBlock;
    }
    if (basename === "/") {
      return shouldBlock(arg);
    }

    // If they provided us a function and we've got an active basename, strip
    // it from the locations we expose to the user to match the behavior of
    // useLocation
    let {
      currentLocation,
      nextLocation,
      historyAction
    } = arg;
    return shouldBlock({
      currentLocation: _extends({}, currentLocation, {
        pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
      }),
      nextLocation: _extends({}, nextLocation, {
        pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
      }),
      historyAction
    });
  }, [basename, shouldBlock]);

  // This effect is in charge of blocker key assignment and deletion (which is
  // tightly coupled to the key)
  React.useEffect(() => {
    let key = String(++blockerId);
    setBlockerKey(key);
    return () => router.deleteBlocker(key);
  }, [router]);

  // This effect handles assigning the blockerFunction.  This is to handle
  // unstable blocker function identities, and happens only after the prior
  // effect so we don't get an orphaned blockerFunction in the router with a
  // key of "".  Until then we just have the IDLE_BLOCKER.
  React.useEffect(() => {
    if (blockerKey !== "") {
      router.getBlocker(blockerKey, blockerFunction);
    }
  }, [router, blockerKey, blockerFunction]);

  // Prefer the blocker from `state` not `router.state` since DataRouterContext
  // is memoized so this ensures we update on blocker state updates
  return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
}

/**
 * Stable version of useNavigate that is used when we are in the context of
 * a RouterProvider.
 */
function useNavigateStable() {
  let {
    router
  } = useDataRouterContext(DataRouterHook.UseNavigateStable);
  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
  let activeRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(false);
  useIsomorphicLayoutEffect(() => {
    activeRef.current = true;
  });
  let navigate = react__WEBPACK_IMPORTED_MODULE_0__.useCallback(function (to, options) {
    if (options === void 0) {
      options = {};
    }
     false ? 0 : void 0;

    // Short circuit here since if this happens on first render the navigate
    // is useless because we haven't wired up our router subscriber yet
    if (!activeRef.current) return;
    if (typeof to === "number") {
      router.navigate(to);
    } else {
      router.navigate(to, _extends({
        fromRouteId: id
      }, options));
    }
  }, [router, id]);
  return navigate;
}
const alreadyWarned = {};
function warningOnce(key, cond, message) {
  if (!cond && !alreadyWarned[key]) {
    alreadyWarned[key] = true;
     false ? 0 : void 0;
  }
}

/**
  Webpack + React 17 fails to compile on any of the following because webpack
  complains that `startTransition` doesn't exist in `React`:
  * import { startTransition } from "react"
  * import * as React from from "react";
    "startTransition" in React ? React.startTransition(() => setState()) : setState()
  * import * as React from from "react";
    "startTransition" in React ? React["startTransition"](() => setState()) : setState()

  Moving it to a constant such as the following solves the Webpack/React 17 issue:
  * import * as React from from "react";
    const START_TRANSITION = "startTransition";
    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()

  However, that introduces webpack/terser minification issues in production builds
  in React 18 where minification/obfuscation ends up removing the call of
  React.startTransition entirely from the first half of the ternary.  Grabbing
  this exported reference once up front resolves that issue.

  See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = /*#__PURE__*/ (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_0__, 2)))[START_TRANSITION];

/**
 * Given a Remix Router instance, render the appropriate UI
 */
function RouterProvider(_ref) {
  let {
    fallbackElement,
    router,
    future
  } = _ref;
  let [state, setStateImpl] = React.useState(router.state);
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    if (v7_startTransition && startTransitionImpl) {
      startTransitionImpl(() => setStateImpl(newState));
    } else {
      setStateImpl(newState);
    }
  }, [setStateImpl, v7_startTransition]);

  // Need to use a layout effect here so we are subscribed early enough to
  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  React.useEffect(() => {
     false ? 0 : void 0;
    // Only log this once on initial mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  let navigator = React.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: n => router.navigate(n),
      push: (to, state, opts) => router.navigate(to, {
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      }),
      replace: (to, state, opts) => router.navigate(to, {
        replace: true,
        state,
        preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
      })
    };
  }, [router]);
  let basename = router.basename || "/";
  let dataRouterContext = React.useMemo(() => ({
    router,
    navigator,
    static: false,
    basename
  }), [router, navigator, basename]);

  // The fragment and {null} here are important!  We need them to keep React 18's
  // useId happy when we are server-rendering since we may have a <script> here
  // containing the hydrated server-side staticContext (from StaticRouterProvider).
  // useId relies on the component tree structure to generate deterministic id's
  // so we need to ensure it remains the same on the client even though
  // we don't need the <script> tag
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
    value: dataRouterContext
  }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
    value: state
  }, /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    location: state.location,
    navigationType: state.historyAction,
    navigator: navigator,
    future: {
      v7_relativeSplatPath: router.future.v7_relativeSplatPath
    }
  }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, {
    routes: router.routes,
    future: router.future,
    state: state
  }) : fallbackElement))), null);
}
function DataRoutes(_ref2) {
  let {
    routes,
    future,
    state
  } = _ref2;
  return useRoutesImpl(routes, undefined, state, future);
}
/**
 * A `<Router>` that stores all entries in memory.
 *
 * @see https://reactrouter.com/router-components/memory-router
 */
function MemoryRouter(_ref3) {
  let {
    basename,
    children,
    initialEntries,
    initialIndex,
    future
  } = _ref3;
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    historyRef.current = createMemoryHistory({
      initialEntries,
      initialIndex,
      v5Compat: true
    });
  }
  let history = historyRef.current;
  let [state, setStateImpl] = React.useState({
    action: history.action,
    location: history.location
  });
  let {
    v7_startTransition
  } = future || {};
  let setState = React.useCallback(newState => {
    v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  }, [setStateImpl, v7_startTransition]);
  React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  return /*#__PURE__*/React.createElement(Router, {
    basename: basename,
    children: children,
    location: state.location,
    navigationType: state.action,
    navigator: history,
    future: future
  });
}
/**
 * Changes the current location.
 *
 * Note: This API is mostly useful in React.Component subclasses that are not
 * able to use hooks. In functional components, we recommend you use the
 * `useNavigate` hook instead.
 *
 * @see https://reactrouter.com/components/navigate
 */
function Navigate(_ref4) {
  let {
    to,
    replace,
    state,
    relative
  } = _ref4;
  !useInRouterContext() ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
  let {
    future,
    static: isStatic
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext);
   false ? 0 : void 0;
  let {
    matches
  } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext);
  let {
    pathname: locationPathname
  } = useLocation();
  let navigate = useNavigate();

  // Resolve the path outside of the effect so that when effects run twice in
  // StrictMode they navigate to the same place
  let path = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .resolveTo */ .Gh)(to, (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_getResolveToMatches */ .yD)(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
  let jsonPath = JSON.stringify(path);
  react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => navigate(JSON.parse(jsonPath), {
    replace,
    state,
    relative
  }), [navigate, jsonPath, relative, replace, state]);
  return null;
}
/**
 * Renders the child route's element, if there is one.
 *
 * @see https://reactrouter.com/components/outlet
 */
function Outlet(props) {
  return useOutlet(props.context);
}
/**
 * Declares an element that should be rendered at a certain URL path.
 *
 * @see https://reactrouter.com/components/route
 */
function Route(_props) {
   false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) ;
}
/**
 * Provides location context for the rest of the app.
 *
 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
 * router that is more specific to your environment such as a `<BrowserRouter>`
 * in web browsers or a `<StaticRouter>` for server rendering.
 *
 * @see https://reactrouter.com/router-components/router
 */
function Router(_ref5) {
  let {
    basename: basenameProp = "/",
    children = null,
    location: locationProp,
    navigationType = _remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .Action */ .rc.Pop,
    navigator,
    static: staticProp = false,
    future
  } = _ref5;
  !!useInRouterContext() ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;

  // Preserve trailing slashes on basename, so we can let the user control
  // the enforcement of trailing slashes throughout the app
  let basename = basenameProp.replace(/^\/*/, "/");
  let navigationContext = react__WEBPACK_IMPORTED_MODULE_0__.useMemo(() => ({
    basename,
    navigator,
    static: staticProp,
    future: _extends({
      v7_relativeSplatPath: false
    }, future)
  }), [basename, future, navigator, staticProp]);
  if (typeof locationProp === "string") {
    locationProp = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .parsePath */ .Rr)(locationProp);
  }
  let {
    pathname = "/",
    search = "",
    hash = "",
    state = null,
    key = "default"
  } = locationProp;
  let locationContext = react__WEBPACK_IMPORTED_MODULE_0__.useMemo(() => {
    let trailingPathname = (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .stripBasename */ .pb)(pathname, basename);
    if (trailingPathname == null) {
      return null;
    }
    return {
      location: {
        pathname: trailingPathname,
        search,
        hash,
        state,
        key
      },
      navigationType
    };
  }, [basename, pathname, search, hash, state, key, navigationType]);
   false ? 0 : void 0;
  if (locationContext == null) {
    return null;
  }
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(NavigationContext.Provider, {
    value: navigationContext
  }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(LocationContext.Provider, {
    children: children,
    value: locationContext
  }));
}
/**
 * A container for a nested tree of `<Route>` elements that renders the branch
 * that best matches the current location.
 *
 * @see https://reactrouter.com/components/routes
 */
function Routes(_ref6) {
  let {
    children,
    location
  } = _ref6;
  return useRoutes(createRoutesFromChildren(children), location);
}
/**
 * Component to use for rendering lazily loaded data from returning defer()
 * in a loader function
 */
function Await(_ref7) {
  let {
    children,
    errorElement,
    resolve
  } = _ref7;
  return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
    resolve: resolve,
    errorElement: errorElement
  }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
}
var AwaitRenderStatus = /*#__PURE__*/function (AwaitRenderStatus) {
  AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
  AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
  AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
  return AwaitRenderStatus;
}(AwaitRenderStatus || {});
const neverSettledPromise = new Promise(() => {});
class AwaitErrorBoundary extends react__WEBPACK_IMPORTED_MODULE_0__.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null
    };
  }
  static getDerivedStateFromError(error) {
    return {
      error
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error("<Await> caught the following error during render", error, errorInfo);
  }
  render() {
    let {
      children,
      errorElement,
      resolve
    } = this.props;
    let promise = null;
    let status = AwaitRenderStatus.pending;
    if (!(resolve instanceof Promise)) {
      // Didn't get a promise - provide as a resolved promise
      status = AwaitRenderStatus.success;
      promise = Promise.resolve();
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_data", {
        get: () => resolve
      });
    } else if (this.state.error) {
      // Caught a render error, provide it as a rejected promise
      status = AwaitRenderStatus.error;
      let renderError = this.state.error;
      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
      Object.defineProperty(promise, "_tracked", {
        get: () => true
      });
      Object.defineProperty(promise, "_error", {
        get: () => renderError
      });
    } else if (resolve._tracked) {
      // Already tracked promise - check contents
      promise = resolve;
      status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
    } else {
      // Raw (untracked) promise - track it
      status = AwaitRenderStatus.pending;
      Object.defineProperty(resolve, "_tracked", {
        get: () => true
      });
      promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
        get: () => data
      }), error => Object.defineProperty(resolve, "_error", {
        get: () => error
      }));
    }
    if (status === AwaitRenderStatus.error && promise._error instanceof _remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .AbortedDeferredError */ .tH) {
      // Freeze the UI by throwing a never resolved promise
      throw neverSettledPromise;
    }
    if (status === AwaitRenderStatus.error && !errorElement) {
      // No errorElement, throw to the nearest route-level error boundary
      throw promise._error;
    }
    if (status === AwaitRenderStatus.error) {
      // Render via our errorElement
      return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(AwaitContext.Provider, {
        value: promise,
        children: errorElement
      });
    }
    if (status === AwaitRenderStatus.success) {
      // Render children with resolved value
      return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement(AwaitContext.Provider, {
        value: promise,
        children: children
      });
    }

    // Throw to the suspense boundary
    throw promise;
  }
}

/**
 * @private
 * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
 */
function ResolveAwait(_ref8) {
  let {
    children
  } = _ref8;
  let data = useAsyncValue();
  let toRender = typeof children === "function" ? children(data) : children;
  return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
}

///////////////////////////////////////////////////////////////////////////////
// UTILS
///////////////////////////////////////////////////////////////////////////////

/**
 * Creates a route config from a React "children" object, which is usually
 * either a `<Route>` element or an array of them. Used internally by
 * `<Routes>` to create a route config from its children.
 *
 * @see https://reactrouter.com/utils/create-routes-from-children
 */
function createRoutesFromChildren(children, parentPath) {
  if (parentPath === void 0) {
    parentPath = [];
  }
  let routes = [];
  react__WEBPACK_IMPORTED_MODULE_0__.Children.forEach(children, (element, index) => {
    if (! /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.isValidElement(element)) {
      // Ignore non-elements. This allows people to more easily inline
      // conditionals in their route config.
      return;
    }
    let treePath = [...parentPath, index];
    if (element.type === react__WEBPACK_IMPORTED_MODULE_0__.Fragment) {
      // Transparently support React.Fragment and its children.
      routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
      return;
    }
    !(element.type === Route) ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
    !(!element.props.index || !element.props.children) ?  false ? 0 : (0,_remix_run_router__WEBPACK_IMPORTED_MODULE_1__/* .UNSAFE_invariant */ .Oi)(false) : void 0;
    let route = {
      id: element.props.id || treePath.join("-"),
      caseSensitive: element.props.caseSensitive,
      element: element.props.element,
      Component: element.props.Component,
      index: element.props.index,
      path: element.props.path,
      loader: element.props.loader,
      action: element.props.action,
      errorElement: element.props.errorElement,
      ErrorBoundary: element.props.ErrorBoundary,
      hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
      shouldRevalidate: element.props.shouldRevalidate,
      handle: element.props.handle,
      lazy: element.props.lazy
    };
    if (element.props.children) {
      route.children = createRoutesFromChildren(element.props.children, treePath);
    }
    routes.push(route);
  });
  return routes;
}

/**
 * Renders the result of `matchRoutes()` into a React element.
 */
function renderMatches(matches) {
  return _renderMatches(matches);
}

function mapRouteProperties(route) {
  let updates = {
    // Note: this check also occurs in createRoutesFromChildren so update
    // there if you change this -- please and thank you!
    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
  };
  if (route.Component) {
    if (false) // removed by dead control flow
{}
    Object.assign(updates, {
      element: /*#__PURE__*/React.createElement(route.Component),
      Component: undefined
    });
  }
  if (route.HydrateFallback) {
    if (false) // removed by dead control flow
{}
    Object.assign(updates, {
      hydrateFallbackElement: /*#__PURE__*/React.createElement(route.HydrateFallback),
      HydrateFallback: undefined
    });
  }
  if (route.ErrorBoundary) {
    if (false) // removed by dead control flow
{}
    Object.assign(updates, {
      errorElement: /*#__PURE__*/React.createElement(route.ErrorBoundary),
      ErrorBoundary: undefined
    });
  }
  return updates;
}
function createMemoryRouter(routes, opts) {
  return createRouter({
    basename: opts == null ? void 0 : opts.basename,
    future: _extends({}, opts == null ? void 0 : opts.future, {
      v7_prependBasename: true
    }),
    history: createMemoryHistory({
      initialEntries: opts == null ? void 0 : opts.initialEntries,
      initialIndex: opts == null ? void 0 : opts.initialIndex
    }),
    hydrationData: opts == null ? void 0 : opts.hydrationData,
    routes,
    mapRouteProperties
  }).initialize();
}


//# sourceMappingURL=index.js.map


/***/ }),

/***/ 7965:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";


var deselectCurrent = __webpack_require__(6426);

var clipboardToIE11Formatting = {
  "text/plain": "Text",
  "text/html": "Url",
  "default": "Text"
}

var defaultMessage = "Copy to clipboard: #{key}, Enter";

function format(message) {
  var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C";
  return message.replace(/#{\s*key\s*}/g, copyKey);
}

function copy(text, options) {
  var debug,
    message,
    reselectPrevious,
    range,
    selection,
    mark,
    success = false;
  if (!options) {
    options = {};
  }
  debug = options.debug || false;
  try {
    reselectPrevious = deselectCurrent();

    range = document.createRange();
    selection = document.getSelection();

    mark = document.createElement("span");
    mark.textContent = text;
    // avoid screen readers from reading out loud the text
    mark.ariaHidden = "true"
    // reset user styles for span element
    mark.style.all = "unset";
    // prevents scrolling to the end of the page
    mark.style.position = "fixed";
    mark.style.top = 0;
    mark.style.clip = "rect(0, 0, 0, 0)";
    // used to preserve spaces and line breaks
    mark.style.whiteSpace = "pre";
    // do not inherit user-select (it may be `none`)
    mark.style.webkitUserSelect = "text";
    mark.style.MozUserSelect = "text";
    mark.style.msUserSelect = "text";
    mark.style.userSelect = "text";
    mark.addEventListener("copy", function(e) {
      e.stopPropagation();
      if (options.format) {
        e.preventDefault();
        if (typeof e.clipboardData === "undefined") { // IE 11
          debug && console.warn("unable to use e.clipboardData");
          debug && console.warn("trying IE specific stuff");
          window.clipboardData.clearData();
          var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]
          window.clipboardData.setData(format, text);
        } else { // all other browsers
          e.clipboardData.clearData();
          e.clipboardData.setData(options.format, text);
        }
      }
      if (options.onCopy) {
        e.preventDefault();
        options.onCopy(e.clipboardData);
      }
    });

    document.body.appendChild(mark);

    range.selectNodeContents(mark);
    selection.addRange(range);

    var successful = document.execCommand("copy");
    if (!successful) {
      throw new Error("copy command was unsuccessful");
    }
    success = true;
  } catch (err) {
    debug && console.error("unable to copy using execCommand: ", err);
    debug && console.warn("trying IE specific stuff");
    try {
      window.clipboardData.setData(options.format || "text", text);
      options.onCopy && options.onCopy(window.clipboardData);
      success = true;
    } catch (err) {
      debug && console.error("unable to copy using clipboardData: ", err);
      debug && console.error("falling back to prompt");
      message = format("message" in options ? options.message : defaultMessage);
      window.prompt(message, text);
    }
  } finally {
    if (selection) {
      if (typeof selection.removeRange == "function") {
        selection.removeRange(range);
      } else {
        selection.removeAllRanges();
      }
    }

    if (mark) {
      document.body.removeChild(mark);
    }
    reselectPrevious();
  }

  return success;
}

module.exports = copy;


/***/ }),

/***/ 8168:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: function() { return /* binding */ _extends; }
/* harmony export */ });
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}


/***/ }),

/***/ 8171:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TabNode = void 0;
const Attribute_1 = __webpack_require__(46);
const AttributeDefinitions_1 = __webpack_require__(6874);
const Node_1 = __webpack_require__(7618);
class TabNode extends Node_1.Node {
    /** @internal */
    static _fromJson(json, model, addToModel = true) {
        const newLayoutNode = new TabNode(model, json, addToModel);
        return newLayoutNode;
    }
    /** @internal */
    static _createAttributeDefinitions() {
        const attributeDefinitions = new AttributeDefinitions_1.AttributeDefinitions();
        attributeDefinitions.add("type", TabNode.TYPE, true).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("id", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("name", "[Unnamed Tab]").setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("altName", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("helpText", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("component", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("config", undefined).setType("any");
        attributeDefinitions.add("floating", false).setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.add("tabsetClassName", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.addInherited("enableClose", "tabEnableClose").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("closeType", "tabCloseType").setType("ICloseType");
        attributeDefinitions.addInherited("enableDrag", "tabEnableDrag").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("enableRename", "tabEnableRename").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("className", "tabClassName").setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.addInherited("contentClassName", "tabContentClassName").setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.addInherited("icon", "tabIcon").setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.addInherited("enableRenderOnDemand", "tabEnableRenderOnDemand").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("enableFloat", "tabEnableFloat").setType(Attribute_1.Attribute.BOOLEAN);
        attributeDefinitions.addInherited("borderWidth", "tabBorderWidth").setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.addInherited("borderHeight", "tabBorderHeight").setType(Attribute_1.Attribute.NUMBER);
        return attributeDefinitions;
    }
    /** @internal */
    constructor(model, json, addToModel = true) {
        super(model);
        this._extra = {}; // extra data added to node not saved in json
        TabNode._attributeDefinitions.fromJson(json, this._attributes);
        if (addToModel === true) {
            model._addNode(this);
        }
    }
    getWindow() {
        return this._window;
    }
    getTabRect() {
        return this._tabRect;
    }
    /** @internal */
    _setTabRect(rect) {
        this._tabRect = rect;
    }
    /** @internal */
    _setRenderedName(name) {
        this._renderedName = name;
    }
    /** @internal */
    _getNameForOverflowMenu() {
        const altName = this._getAttr("altName");
        if (altName !== undefined) {
            return altName;
        }
        return this._renderedName;
    }
    getName() {
        return this._getAttr("name");
    }
    getHelpText() {
        return this._getAttr("helpText");
    }
    getComponent() {
        return this._getAttr("component");
    }
    /**
     * Returns the config attribute that can be used to store node specific data that
     * WILL be saved to the json. The config attribute should be changed via the action Actions.updateNodeAttributes rather
     * than directly, for example:
     * this.state.model.doAction(
     *   FlexLayout.Actions.updateNodeAttributes(node.getId(), {config:myConfigObject}));
     */
    getConfig() {
        return this._attributes.config;
    }
    /**
     * Returns an object that can be used to store transient node specific data that will
     * NOT be saved in the json.
     */
    getExtraData() {
        return this._extra;
    }
    isFloating() {
        return this._getAttr("floating");
    }
    getIcon() {
        return this._getAttr("icon");
    }
    isEnableClose() {
        return this._getAttr("enableClose");
    }
    getCloseType() {
        return this._getAttr("closeType");
    }
    isEnableFloat() {
        return this._getAttr("enableFloat");
    }
    isEnableDrag() {
        return this._getAttr("enableDrag");
    }
    isEnableRename() {
        return this._getAttr("enableRename");
    }
    getClassName() {
        return this._getAttr("className");
    }
    getContentClassName() {
        return this._getAttr("contentClassName");
    }
    getTabSetClassName() {
        return this._getAttr("tabsetClassName");
    }
    isEnableRenderOnDemand() {
        return this._getAttr("enableRenderOnDemand");
    }
    /** @internal */
    _setName(name) {
        this._attributes.name = name;
        if (this._window && this._window.document) {
            this._window.document.title = name;
        }
    }
    /** @internal */
    _setFloating(float) {
        this._attributes.floating = float;
    }
    /** @internal */
    _layout(rect, metrics) {
        if (!rect.equals(this._rect)) {
            this._fireEvent("resize", { rect });
        }
        this._rect = rect;
    }
    /** @internal */
    _delete() {
        this._parent._remove(this);
        this._fireEvent("close", {});
    }
    toJson() {
        const json = {};
        TabNode._attributeDefinitions.toJson(json, this._attributes);
        return json;
    }
    /** @internal */
    _updateAttrs(json) {
        TabNode._attributeDefinitions.update(json, this._attributes);
    }
    /** @internal */
    _getAttributeDefinitions() {
        return TabNode._attributeDefinitions;
    }
    /** @internal */
    _setWindow(window) {
        this._window = window;
    }
    /** @internal */
    _setBorderWidth(width) {
        this._attributes.borderWidth = width;
    }
    /** @internal */
    _setBorderHeight(height) {
        this._attributes.borderHeight = height;
    }
    /** @internal */
    static getAttributeDefinitions() {
        return TabNode._attributeDefinitions;
    }
}
exports.TabNode = TabNode;
TabNode.TYPE = "tab";
/** @internal */
TabNode._attributeDefinitions = TabNode._createAttributeDefinitions();
//# sourceMappingURL=TabNode.js.map

/***/ }),

/***/ 8324:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DockLocation = void 0;
const Orientation_1 = __webpack_require__(1648);
const Rect_1 = __webpack_require__(2530);
class DockLocation {
    /** @internal */
    static getByName(name) {
        return DockLocation.values[name];
    }
    /** @internal */
    static getLocation(rect, x, y) {
        x = (x - rect.x) / rect.width;
        y = (y - rect.y) / rect.height;
        if (x >= 0.25 && x < 0.75 && y >= 0.25 && y < 0.75) {
            return DockLocation.CENTER;
        }
        // Whether or not the point is in the bottom-left half of the rect
        // +-----+
        // |\    |
        // |x\   |
        // |xx\  |
        // |xxx\ |
        // |xxxx\|
        // +-----+
        const bl = y >= x;
        // Whether or not the point is in the bottom-right half of the rect
        // +-----+
        // |    /|
        // |   /x|
        // |  /xx|
        // | /xxx|
        // |/xxxx|
        // +-----+
        const br = y >= 1 - x;
        if (bl) {
            return br ? DockLocation.BOTTOM : DockLocation.LEFT;
        }
        else {
            return br ? DockLocation.RIGHT : DockLocation.TOP;
        }
    }
    /** @internal */
    constructor(name, orientation, indexPlus) {
        this._name = name;
        this._orientation = orientation;
        this._indexPlus = indexPlus;
        DockLocation.values[this._name] = this;
    }
    getName() {
        return this._name;
    }
    getOrientation() {
        return this._orientation;
    }
    /** @internal */
    getDockRect(r) {
        if (this === DockLocation.TOP) {
            return new Rect_1.Rect(r.x, r.y, r.width, r.height / 2);
        }
        else if (this === DockLocation.BOTTOM) {
            return new Rect_1.Rect(r.x, r.getBottom() - r.height / 2, r.width, r.height / 2);
        }
        if (this === DockLocation.LEFT) {
            return new Rect_1.Rect(r.x, r.y, r.width / 2, r.height);
        }
        else if (this === DockLocation.RIGHT) {
            return new Rect_1.Rect(r.getRight() - r.width / 2, r.y, r.width / 2, r.height);
        }
        else {
            return r.clone();
        }
    }
    /** @internal */
    split(rect, size) {
        if (this === DockLocation.TOP) {
            const r1 = new Rect_1.Rect(rect.x, rect.y, rect.width, size);
            const r2 = new Rect_1.Rect(rect.x, rect.y + size, rect.width, rect.height - size);
            return { start: r1, end: r2 };
        }
        else if (this === DockLocation.LEFT) {
            const r1 = new Rect_1.Rect(rect.x, rect.y, size, rect.height);
            const r2 = new Rect_1.Rect(rect.x + size, rect.y, rect.width - size, rect.height);
            return { start: r1, end: r2 };
        }
        if (this === DockLocation.RIGHT) {
            const r1 = new Rect_1.Rect(rect.getRight() - size, rect.y, size, rect.height);
            const r2 = new Rect_1.Rect(rect.x, rect.y, rect.width - size, rect.height);
            return { start: r1, end: r2 };
        }
        else {
            // if (this === DockLocation.BOTTOM) {
            const r1 = new Rect_1.Rect(rect.x, rect.getBottom() - size, rect.width, size);
            const r2 = new Rect_1.Rect(rect.x, rect.y, rect.width, rect.height - size);
            return { start: r1, end: r2 };
        }
    }
    /** @internal */
    reflect() {
        if (this === DockLocation.TOP) {
            return DockLocation.BOTTOM;
        }
        else if (this === DockLocation.LEFT) {
            return DockLocation.RIGHT;
        }
        if (this === DockLocation.RIGHT) {
            return DockLocation.LEFT;
        }
        else {
            // if (this === DockLocation.BOTTOM) {
            return DockLocation.TOP;
        }
    }
    toString() {
        return "(DockLocation: name=" + this._name + ", orientation=" + this._orientation + ")";
    }
}
exports.DockLocation = DockLocation;
DockLocation.values = {};
DockLocation.TOP = new DockLocation("top", Orientation_1.Orientation.VERT, 0);
DockLocation.BOTTOM = new DockLocation("bottom", Orientation_1.Orientation.VERT, 1);
DockLocation.LEFT = new DockLocation("left", Orientation_1.Orientation.HORZ, 0);
DockLocation.RIGHT = new DockLocation("right", Orientation_1.Orientation.HORZ, 1);
DockLocation.CENTER = new DockLocation("center", Orientation_1.Orientation.VERT, 0);
//# sourceMappingURL=DockLocation.js.map

/***/ }),

/***/ 8493:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";
/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */


var React = __webpack_require__(6540);
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
  useState = React.useState,
  useEffect = React.useEffect,
  useLayoutEffect = React.useLayoutEffect,
  useDebugValue = React.useDebugValue;
function useSyncExternalStore$2(subscribe, getSnapshot) {
  var value = getSnapshot(),
    _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),
    inst = _useState[0].inst,
    forceUpdate = _useState[1];
  useLayoutEffect(
    function () {
      inst.value = value;
      inst.getSnapshot = getSnapshot;
      checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
    },
    [subscribe, value, getSnapshot]
  );
  useEffect(
    function () {
      checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
      return subscribe(function () {
        checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
      });
    },
    [subscribe]
  );
  useDebugValue(value);
  return value;
}
function checkIfSnapshotChanged(inst) {
  var latestGetSnapshot = inst.getSnapshot;
  inst = inst.value;
  try {
    var nextValue = latestGetSnapshot();
    return !objectIs(inst, nextValue);
  } catch (error) {
    return !0;
  }
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
  return getSnapshot();
}
var shim =
  "undefined" === typeof window ||
  "undefined" === typeof window.document ||
  "undefined" === typeof window.document.createElement
    ? useSyncExternalStore$1
    : useSyncExternalStore$2;
exports.useSyncExternalStore =
  void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;


/***/ }),

/***/ 8528:
/***/ (function(__unused_webpack_module, exports) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=IDraggable.js.map

/***/ }),

/***/ 8587:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: function() { return /* binding */ _objectWithoutPropertiesLoose; }
/* harmony export */ });
function _objectWithoutPropertiesLoose(r, e) {
  if (null == r) return {};
  var t = {};
  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
    if (-1 !== e.indexOf(n)) continue;
    t[n] = r[n];
  }
  return t;
}


/***/ }),

/***/ 8636:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RestoreIcon = exports.PopoutIcon = exports.EdgeIcon = exports.OverflowIcon = exports.MaximizeIcon = exports.CloseIcon = void 0;
const React = __webpack_require__(6540);
const style = { width: "1em", height: "1em", display: "flex", alignItems: "center" };
const CloseIcon = () => {
    return (React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: style, viewBox: "0 0 24 24" },
        React.createElement("path", { fill: "none", d: "M0 0h24v24H0z" }),
        React.createElement("path", { stroke: "var(--color-icon)", fill: "var(--color-icon)", d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" })));
};
exports.CloseIcon = CloseIcon;
const MaximizeIcon = () => {
    return (React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: style, viewBox: "0 0 24 24", fill: "var(--color-icon)" },
        React.createElement("path", { d: "M0 0h24v24H0z", fill: "none" }),
        React.createElement("path", { stroke: "var(--color-icon)", d: "M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" })));
};
exports.MaximizeIcon = MaximizeIcon;
const OverflowIcon = () => {
    return (React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: style, viewBox: "0 0 24 24", fill: "var(--color-icon)" },
        React.createElement("path", { d: "M0 0h24v24H0z", fill: "none" }),
        React.createElement("path", { stroke: "var(--color-icon)", d: "M7 10l5 5 5-5z" })));
};
exports.OverflowIcon = OverflowIcon;
const EdgeIcon = () => {
    return (React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: { display: "block", width: 10, height: 10 }, preserveAspectRatio: "none", viewBox: "0 0 100 100" },
        React.createElement("path", { fill: "var(--color-edge-icon)", stroke: "var(--color-edge-icon)", d: "M10 30 L90 30 l-40 40 Z" })));
};
exports.EdgeIcon = EdgeIcon;
const PopoutIcon = () => {
    return (
    // <svg xmlns="http://www.w3.org/2000/svg"  style={style}  viewBox="0 0 24 24" fill="var(--color-icon)"><path d="M0 0h24v24H0z" fill="none"/><path stroke="var(--color-icon)" d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z"/></svg>
    // <svg xmlns="http://www.w3.org/2000/svg" style={style} fill="none" viewBox="0 0 24 24" stroke="var(--color-icon)" stroke-width="2">
    //     <path stroke-linecap="round" stroke-linejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
    // </svg>
    React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: style, viewBox: "0 0 20 20", fill: "var(--color-icon)" },
        React.createElement("path", { d: "M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z" }),
        React.createElement("path", { d: "M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z" })));
};
exports.PopoutIcon = PopoutIcon;
const RestoreIcon = () => {
    return (React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: style, viewBox: "0 0 24 24", fill: "var(--color-icon)" },
        React.createElement("path", { d: "M0 0h24v24H0z", fill: "none" }),
        React.createElement("path", { stroke: "var(--color-icon)", d: "M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z" })));
};
exports.RestoreIcon = RestoreIcon;
//# sourceMappingURL=Icons.js.map

/***/ }),

/***/ 9026:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BorderSet = void 0;
const Orientation_1 = __webpack_require__(1648);
const BorderNode_1 = __webpack_require__(1480);
class BorderSet {
    /** @internal */
    static _fromJson(json, model) {
        const borderSet = new BorderSet(model);
        borderSet._borders = json.map((borderJson) => BorderNode_1.BorderNode._fromJson(borderJson, model));
        return borderSet;
    }
    /** @internal */
    constructor(model) {
        this._model = model;
        this._borders = [];
    }
    getBorders() {
        return this._borders;
    }
    /** @internal */
    _forEachNode(fn) {
        for (const borderNode of this._borders) {
            fn(borderNode, 0);
            for (const node of borderNode.getChildren()) {
                node._forEachNode(fn, 1);
            }
        }
    }
    /** @internal */
    _toJson() {
        return this._borders.map((borderNode) => borderNode.toJson());
    }
    /** @internal */
    _layoutBorder(outerInnerRects, metrics) {
        const rect = outerInnerRects.outer;
        const rootRow = this._model.getRoot();
        let height = Math.max(0, rect.height - rootRow.getMinHeight());
        let width = Math.max(0, rect.width - rootRow.getMinWidth());
        let sumHeight = 0;
        let sumWidth = 0;
        let adjustableHeight = 0;
        let adjustableWidth = 0;
        const showingBorders = this._borders.filter((border) => border.isShowing());
        // sum size of borders to see they will fit
        for (const border of showingBorders) {
            border._setAdjustedSize(border.getSize());
            const visible = border.getSelected() !== -1;
            if (border.getLocation().getOrientation() === Orientation_1.Orientation.HORZ) {
                sumWidth += border.getBorderBarSize();
                if (visible) {
                    width -= this._model.getSplitterSize();
                    sumWidth += border.getSize();
                    adjustableWidth += border.getSize();
                }
            }
            else {
                sumHeight += border.getBorderBarSize();
                if (visible) {
                    height -= this._model.getSplitterSize();
                    sumHeight += border.getSize();
                    adjustableHeight += border.getSize();
                }
            }
        }
        // adjust border sizes if too large
        let j = 0;
        let adjusted = false;
        while ((sumWidth > width && adjustableWidth > 0) || (sumHeight > height && adjustableHeight > 0)) {
            const border = showingBorders[j];
            if (border.getSelected() !== -1) {
                // visible
                const size = border._getAdjustedSize();
                if (sumWidth > width && adjustableWidth > 0 && border.getLocation().getOrientation() === Orientation_1.Orientation.HORZ && size > 0
                    && size > border.getMinSize()) {
                    border._setAdjustedSize(size - 1);
                    sumWidth--;
                    adjustableWidth--;
                    adjusted = true;
                }
                else if (sumHeight > height && adjustableHeight > 0 && border.getLocation().getOrientation() === Orientation_1.Orientation.VERT && size > 0
                    && size > border.getMinSize()) {
                    border._setAdjustedSize(size - 1);
                    sumHeight--;
                    adjustableHeight--;
                    adjusted = true;
                }
            }
            j = (j + 1) % showingBorders.length;
            if (j === 0) {
                if (adjusted) {
                    adjusted = false;
                }
                else {
                    break;
                }
            }
        }
        for (const border of showingBorders) {
            outerInnerRects.outer = border._layoutBorderOuter(outerInnerRects.outer, metrics);
        }
        outerInnerRects.inner = outerInnerRects.outer;
        for (const border of showingBorders) {
            outerInnerRects.inner = border._layoutBorderInner(outerInnerRects.inner, metrics);
        }
        return outerInnerRects;
    }
    /** @internal */
    _findDropTargetNode(dragNode, x, y) {
        for (const border of this._borders) {
            if (border.isShowing()) {
                const dropInfo = border.canDrop(dragNode, x, y);
                if (dropInfo !== undefined) {
                    return dropInfo;
                }
            }
        }
        return undefined;
    }
}
exports.BorderSet = BorderSet;
//# sourceMappingURL=BorderSet.js.map

/***/ }),

/***/ 9103:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Actions = void 0;
const Action_1 = __webpack_require__(1200);
/**
 * The Action creator class for FlexLayout model actions
 */
class Actions {
    /**
     * Adds a tab node to the given tabset node
     * @param json the json for the new tab node e.g {type:"tab", component:"table"}
     * @param toNodeId the new tab node will be added to the tabset with this node id
     * @param location the location where the new tab will be added, one of the DockLocation enum values.
     * @param index for docking to the center this value is the index of the tab, use -1 to add to the end.
     * @param select (optional) whether to select the new tab, overriding autoSelectTab
     * @returns {Action} the action
     */
    static addNode(json, toNodeId, location, index, select) {
        return new Action_1.Action(Actions.ADD_NODE, {
            json,
            toNode: toNodeId,
            location: location.getName(),
            index,
            select,
        });
    }
    /**
     * Moves a node (tab or tabset) from one location to another
     * @param fromNodeId the id of the node to move
     * @param toNodeId the id of the node to receive the moved node
     * @param location the location where the moved node will be added, one of the DockLocation enum values.
     * @param index for docking to the center this value is the index of the tab, use -1 to add to the end.
     * @param select (optional) whether to select the moved tab(s) in new tabset, overriding autoSelectTab
     * @returns {Action} the action
     */
    static moveNode(fromNodeId, toNodeId, location, index, select) {
        return new Action_1.Action(Actions.MOVE_NODE, {
            fromNode: fromNodeId,
            toNode: toNodeId,
            location: location.getName(),
            index,
            select,
        });
    }
    /**
     * Deletes a tab node from the layout
     * @param tabsetNodeId the id of the tab node to delete
     * @returns {Action} the action
     */
    static deleteTab(tabNodeId) {
        return new Action_1.Action(Actions.DELETE_TAB, { node: tabNodeId });
    }
    /**
     * Deletes a tabset node and all it's child tab nodes from the layout
     * @param tabsetNodeId the id of the tabset node to delete
     * @returns {Action} the action
     */
    static deleteTabset(tabsetNodeId) {
        return new Action_1.Action(Actions.DELETE_TABSET, { node: tabsetNodeId });
    }
    /**
     * Change the given nodes tab text
     * @param tabNodeId the id of the node to rename
     * @param text the test of the tab
     * @returns {Action} the action
     */
    static renameTab(tabNodeId, text) {
        return new Action_1.Action(Actions.RENAME_TAB, { node: tabNodeId, text });
    }
    /**
     * Selects the given tab in its parent tabset
     * @param tabNodeId the id of the node to set selected
     * @returns {Action} the action
     */
    static selectTab(tabNodeId) {
        return new Action_1.Action(Actions.SELECT_TAB, { tabNode: tabNodeId });
    }
    /**
     * Set the given tabset node as the active tabset
     * @param tabsetNodeId the id of the tabset node to set as active
     * @returns {Action} the action
     */
    static setActiveTabset(tabsetNodeId) {
        return new Action_1.Action(Actions.SET_ACTIVE_TABSET, { tabsetNode: tabsetNodeId });
    }
    /**
     * Adjust the splitter between two tabsets
     * @example
     *  Actions.adjustSplit({node1: "1", weight1:30, pixelWidth1:300, node2: "2", weight2:70, pixelWidth2:700});
     *
     * @param splitSpec an object the defines the new split between two tabsets, see example below.
     * @returns {Action} the action
     */
    static adjustSplit(splitSpec) {
        const node1 = splitSpec.node1Id;
        const node2 = splitSpec.node2Id;
        return new Action_1.Action(Actions.ADJUST_SPLIT, {
            node1,
            weight1: splitSpec.weight1,
            pixelWidth1: splitSpec.pixelWidth1,
            node2,
            weight2: splitSpec.weight2,
            pixelWidth2: splitSpec.pixelWidth2,
        });
    }
    static adjustBorderSplit(nodeId, pos) {
        return new Action_1.Action(Actions.ADJUST_BORDER_SPLIT, { node: nodeId, pos });
    }
    /**
     * Maximizes the given tabset
     * @param tabsetNodeId the id of the tabset to maximize
     * @returns {Action} the action
     */
    static maximizeToggle(tabsetNodeId) {
        return new Action_1.Action(Actions.MAXIMIZE_TOGGLE, { node: tabsetNodeId });
    }
    /**
     * Updates the global model jsone attributes
     * @param attributes the json for the model attributes to update (merge into the existing attributes)
     * @returns {Action} the action
     */
    static updateModelAttributes(attributes) {
        return new Action_1.Action(Actions.UPDATE_MODEL_ATTRIBUTES, { json: attributes });
    }
    /**
     * Updates the given nodes json attributes
     * @param nodeId the id of the node to update
     * @param attributes the json attributes to update (merge with the existing attributes)
     * @returns {Action} the action
     */
    static updateNodeAttributes(nodeId, attributes) {
        return new Action_1.Action(Actions.UPDATE_NODE_ATTRIBUTES, { node: nodeId, json: attributes });
    }
    static floatTab(nodeId) {
        return new Action_1.Action(Actions.FLOAT_TAB, { node: nodeId });
    }
    static unFloatTab(nodeId) {
        return new Action_1.Action(Actions.UNFLOAT_TAB, { node: nodeId });
    }
}
exports.Actions = Actions;
Actions.ADD_NODE = "FlexLayout_AddNode";
Actions.MOVE_NODE = "FlexLayout_MoveNode";
Actions.DELETE_TAB = "FlexLayout_DeleteTab";
Actions.DELETE_TABSET = "FlexLayout_DeleteTabset";
Actions.RENAME_TAB = "FlexLayout_RenameTab";
Actions.SELECT_TAB = "FlexLayout_SelectTab";
Actions.SET_ACTIVE_TABSET = "FlexLayout_SetActiveTabset";
Actions.ADJUST_SPLIT = "FlexLayout_AdjustSplit";
Actions.ADJUST_BORDER_SPLIT = "FlexLayout_AdjustBorderSplit";
Actions.MAXIMIZE_TOGGLE = "FlexLayout_MaximizeToggle";
Actions.UPDATE_MODEL_ATTRIBUTES = "FlexLayout_UpdateModelAttributes";
Actions.UPDATE_NODE_ATTRIBUTES = "FlexLayout_UpdateNodeAttributes";
Actions.FLOAT_TAB = "FlexLayout_FloatTab";
Actions.UNFLOAT_TAB = "FlexLayout_UnFloatTab";
//# sourceMappingURL=Actions.js.map

/***/ }),

/***/ 9242:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(2162);
} else // removed by dead control flow
{}


/***/ }),

/***/ 9310:
/***/ (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;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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 }));
__exportStar(__webpack_require__(7462), exports);
__exportStar(__webpack_require__(1200), exports);
__exportStar(__webpack_require__(9103), exports);
__exportStar(__webpack_require__(1480), exports);
__exportStar(__webpack_require__(9026), exports);
__exportStar(__webpack_require__(5731), exports);
__exportStar(__webpack_require__(8528), exports);
__exportStar(__webpack_require__(3391), exports);
__exportStar(__webpack_require__(3948), exports);
__exportStar(__webpack_require__(7393), exports);
__exportStar(__webpack_require__(7618), exports);
__exportStar(__webpack_require__(4948), exports);
__exportStar(__webpack_require__(6169), exports);
__exportStar(__webpack_require__(8171), exports);
__exportStar(__webpack_require__(9555), exports);
__exportStar(__webpack_require__(8324), exports);
__exportStar(__webpack_require__(883), exports);
__exportStar(__webpack_require__(4017), exports);
__exportStar(__webpack_require__(300), exports);
__exportStar(__webpack_require__(1648), exports);
__exportStar(__webpack_require__(2530), exports);
__exportStar(__webpack_require__(6643), exports);
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 9425:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Tab = void 0;
const React = __webpack_require__(6540);
const react_1 = __webpack_require__(6540);
const Actions_1 = __webpack_require__(9103);
const TabSetNode_1 = __webpack_require__(9555);
const Types_1 = __webpack_require__(6643);
const ErrorBoundary_1 = __webpack_require__(6834);
const I18nLabel_1 = __webpack_require__(300);
const BorderNode_1 = __webpack_require__(1480);
const Utils_1 = __webpack_require__(343);
/** @internal */
const Tab = (props) => {
    const { layout, selected, node, factory, path } = props;
    const [renderComponent, setRenderComponent] = React.useState(!props.node.isEnableRenderOnDemand() || props.selected);
    React.useLayoutEffect(() => {
        if (!renderComponent && selected) {
            // load on demand
            // console.log("load on demand: " + node.getName());
            setRenderComponent(true);
        }
    });
    const onMouseDown = () => {
        const parent = node.getParent();
        if (parent.getType() === TabSetNode_1.TabSetNode.TYPE) {
            if (!parent.isActive()) {
                layout.doAction(Actions_1.Actions.setActiveTabset(parent.getId()));
            }
        }
    };
    const cm = layout.getClassName;
    const useVisibility = node.getModel().isUseVisibility();
    const parentNode = node.getParent();
    const style = node._styleWithPosition();
    if (!selected) {
        (0, Utils_1.hideElement)(style, useVisibility);
    }
    if (parentNode instanceof TabSetNode_1.TabSetNode) {
        if (node.getModel().getMaximizedTabset() !== undefined && !parentNode.isMaximized()) {
            (0, Utils_1.hideElement)(style, useVisibility);
        }
    }
    let child;
    if (renderComponent) {
        child = factory(node);
    }
    let className = cm(Types_1.CLASSES.FLEXLAYOUT__TAB);
    if (parentNode instanceof BorderNode_1.BorderNode) {
        className += " " + cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BORDER);
        className += " " + cm(Types_1.CLASSES.FLEXLAYOUT__TAB_BORDER_ + parentNode.getLocation().getName());
    }
    if (node.getContentClassName() !== undefined) {
        className += " " + node.getContentClassName();
    }
    return (React.createElement("div", { className: className, "data-layout-path": path, onMouseDown: onMouseDown, onTouchStart: onMouseDown, style: style },
        React.createElement(ErrorBoundary_1.ErrorBoundary, { message: props.layout.i18nName(I18nLabel_1.I18nLabel.Error_rendering_component) },
            React.createElement(react_1.Fragment, null, child))));
};
exports.Tab = Tab;
//# sourceMappingURL=Tab.js.map

/***/ }),

/***/ 9555:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TabSetNode = void 0;
const Attribute_1 = __webpack_require__(46);
const AttributeDefinitions_1 = __webpack_require__(6874);
const DockLocation_1 = __webpack_require__(8324);
const DropInfo_1 = __webpack_require__(4017);
const Orientation_1 = __webpack_require__(1648);
const Rect_1 = __webpack_require__(2530);
const Types_1 = __webpack_require__(6643);
const BorderNode_1 = __webpack_require__(1480);
const Node_1 = __webpack_require__(7618);
const RowNode_1 = __webpack_require__(4948);
const TabNode_1 = __webpack_require__(8171);
const Utils_1 = __webpack_require__(2429);
class TabSetNode extends Node_1.Node {
    /** @internal */
    static _fromJson(json, model) {
        const newLayoutNode = new TabSetNode(model, json);
        if (json.children != null) {
            for (const jsonChild of json.children) {
                const child = TabNode_1.TabNode._fromJson(jsonChild, model);
                newLayoutNode._addChild(child);
            }
        }
        if (newLayoutNode._children.length === 0) {
            newLayoutNode._setSelected(-1);
        }
        if (json.maximized && json.maximized === true) {
            model._setMaximizedTabset(newLayoutNode);
        }
        if (json.active && json.active === true) {
            model._setActiveTabset(newLayoutNode);
        }
        return newLayoutNode;
    }
    /** @internal */
    static _createAttributeDefinitions() {
        const attributeDefinitions = new AttributeDefinitions_1.AttributeDefinitions();
        attributeDefinitions.add("type", TabSetNode.TYPE, true).setType(Attribute_1.Attribute.STRING).setFixed();
        attributeDefinitions.add("id", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("weight", 100).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("width", undefined).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("height", undefined).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("selected", 0).setType(Attribute_1.Attribute.NUMBER);
        attributeDefinitions.add("name", undefined).setType(Attribute_1.Attribute.STRING);
        attributeDefinitions.add("config", undefined).setType("any");
        attributeDefinitions.addInherited("enableDeleteWhenEmpty", "tabSetEnableDeleteWhenEmpty");
        attributeDefinitions.addInherited("enableDrop", "tabSetEnableDrop");
        attributeDefinitions.addInherited("enableDrag", "tabSetEnableDrag");
        attributeDefinitions.addInherited("enableDivide", "tabSetEnableDivide");
        attributeDefinitions.addInherited("enableMaximize", "tabSetEnableMaximize");
        attributeDefinitions.addInherited("enableClose", "tabSetEnableClose");
        attributeDefinitions.addInherited("enableSingleTabStretch", "tabSetEnableSingleTabStretch");
        attributeDefinitions.addInherited("classNameTabStrip", "tabSetClassNameTabStrip");
        attributeDefinitions.addInherited("classNameHeader", "tabSetClassNameHeader");
        attributeDefinitions.addInherited("enableTabStrip", "tabSetEnableTabStrip");
        attributeDefinitions.addInherited("borderInsets", "tabSetBorderInsets");
        attributeDefinitions.addInherited("marginInsets", "tabSetMarginInsets");
        attributeDefinitions.addInherited("minWidth", "tabSetMinWidth");
        attributeDefinitions.addInherited("minHeight", "tabSetMinHeight");
        attributeDefinitions.addInherited("headerHeight", "tabSetHeaderHeight");
        attributeDefinitions.addInherited("tabStripHeight", "tabSetTabStripHeight");
        attributeDefinitions.addInherited("tabLocation", "tabSetTabLocation");
        attributeDefinitions.addInherited("autoSelectTab", "tabSetAutoSelectTab").setType(Attribute_1.Attribute.BOOLEAN);
        return attributeDefinitions;
    }
    /** @internal */
    constructor(model, json) {
        super(model);
        TabSetNode._attributeDefinitions.fromJson(json, this._attributes);
        model._addNode(this);
        this._calculatedTabBarHeight = 0;
        this._calculatedHeaderBarHeight = 0;
    }
    getName() {
        return this._getAttr("name");
    }
    getSelected() {
        const selected = this._attributes.selected;
        if (selected !== undefined) {
            return selected;
        }
        return -1;
    }
    getSelectedNode() {
        const selected = this.getSelected();
        if (selected !== -1) {
            return this._children[selected];
        }
        return undefined;
    }
    getWeight() {
        return this._getAttr("weight");
    }
    getWidth() {
        return this._getAttr("width");
    }
    getMinWidth() {
        return this._getAttr("minWidth");
    }
    getHeight() {
        return this._getAttr("height");
    }
    getMinHeight() {
        return this._getAttr("minHeight");
    }
    /** @internal */
    getMinSize(orientation) {
        if (orientation === Orientation_1.Orientation.HORZ) {
            return this.getMinWidth();
        }
        else {
            return this.getMinHeight();
        }
    }
    /**
     * Returns the config attribute that can be used to store node specific data that
     * WILL be saved to the json. The config attribute should be changed via the action Actions.updateNodeAttributes rather
     * than directly, for example:
     * this.state.model.doAction(
     *   FlexLayout.Actions.updateNodeAttributes(node.getId(), {config:myConfigObject}));
     */
    getConfig() {
        return this._attributes.config;
    }
    isMaximized() {
        return this._model.getMaximizedTabset() === this;
    }
    isActive() {
        return this._model.getActiveTabset() === this;
    }
    isEnableDeleteWhenEmpty() {
        return this._getAttr("enableDeleteWhenEmpty");
    }
    isEnableDrop() {
        return this._getAttr("enableDrop");
    }
    isEnableDrag() {
        return this._getAttr("enableDrag");
    }
    isEnableDivide() {
        return this._getAttr("enableDivide");
    }
    isEnableMaximize() {
        return this._getAttr("enableMaximize");
    }
    isEnableClose() {
        return this._getAttr("enableClose");
    }
    isEnableSingleTabStretch() {
        return this._getAttr("enableSingleTabStretch");
    }
    canMaximize() {
        if (this.isEnableMaximize()) {
            // always allow maximize toggle if already maximized
            if (this.getModel().getMaximizedTabset() === this) {
                return true;
            }
            // only one tabset, so disable
            if (this.getParent() === this.getModel().getRoot() && this.getModel().getRoot().getChildren().length === 1) {
                return false;
            }
            return true;
        }
        return false;
    }
    isEnableTabStrip() {
        return this._getAttr("enableTabStrip");
    }
    isAutoSelectTab() {
        return this._getAttr("autoSelectTab");
    }
    getClassNameTabStrip() {
        return this._getAttr("classNameTabStrip");
    }
    getClassNameHeader() {
        return this._getAttr("classNameHeader");
    }
    /** @internal */
    calculateHeaderBarHeight(metrics) {
        const headerBarHeight = this._getAttr("headerHeight");
        if (headerBarHeight !== 0) {
            // its defined
            this._calculatedHeaderBarHeight = headerBarHeight;
        }
        else {
            this._calculatedHeaderBarHeight = metrics.headerBarSize;
        }
    }
    /** @internal */
    calculateTabBarHeight(metrics) {
        const tabBarHeight = this._getAttr("tabStripHeight");
        if (tabBarHeight !== 0) {
            // its defined
            this._calculatedTabBarHeight = tabBarHeight;
        }
        else {
            this._calculatedTabBarHeight = metrics.tabBarSize;
        }
    }
    getHeaderHeight() {
        return this._calculatedHeaderBarHeight;
    }
    getTabStripHeight() {
        return this._calculatedTabBarHeight;
    }
    getTabLocation() {
        return this._getAttr("tabLocation");
    }
    /** @internal */
    _setWeight(weight) {
        this._attributes.weight = weight;
    }
    /** @internal */
    _setSelected(index) {
        this._attributes.selected = index;
    }
    /** @internal */
    canDrop(dragNode, x, y) {
        let dropInfo;
        if (dragNode === this) {
            const dockLocation = DockLocation_1.DockLocation.CENTER;
            const outlineRect = this._tabHeaderRect;
            dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
        }
        else if (this._contentRect.contains(x, y)) {
            let dockLocation = DockLocation_1.DockLocation.CENTER;
            if (this._model.getMaximizedTabset() === undefined) {
                dockLocation = DockLocation_1.DockLocation.getLocation(this._contentRect, x, y);
            }
            const outlineRect = dockLocation.getDockRect(this._rect);
            dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, -1, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
        }
        else if (this._tabHeaderRect != null && this._tabHeaderRect.contains(x, y)) {
            let r;
            let yy;
            let h;
            if (this._children.length === 0) {
                r = this._tabHeaderRect.clone();
                yy = r.y + 3;
                h = r.height - 4;
                r.width = 2;
            }
            else {
                let child = this._children[0];
                r = child.getTabRect();
                yy = r.y;
                h = r.height;
                let p = this._tabHeaderRect.x;
                let childCenter = 0;
                for (let i = 0; i < this._children.length; i++) {
                    child = this._children[i];
                    r = child.getTabRect();
                    childCenter = r.x + r.width / 2;
                    if (x >= p && x < childCenter) {
                        const dockLocation = DockLocation_1.DockLocation.CENTER;
                        const outlineRect = new Rect_1.Rect(r.x - 2, yy, 3, h);
                        dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, i, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
                        break;
                    }
                    p = childCenter;
                }
            }
            if (dropInfo == null) {
                const dockLocation = DockLocation_1.DockLocation.CENTER;
                const outlineRect = new Rect_1.Rect(r.getRight() - 2, yy, 3, h);
                dropInfo = new DropInfo_1.DropInfo(this, outlineRect, dockLocation, this._children.length, Types_1.CLASSES.FLEXLAYOUT__OUTLINE_RECT);
            }
        }
        if (!dragNode._canDockInto(dragNode, dropInfo)) {
            return undefined;
        }
        return dropInfo;
    }
    /** @internal */
    _layout(rect, metrics) {
        this.calculateHeaderBarHeight(metrics);
        this.calculateTabBarHeight(metrics);
        if (this.isMaximized()) {
            rect = this._model.getRoot().getRect();
        }
        rect = rect.removeInsets(this._getAttr("marginInsets"));
        this._rect = rect;
        rect = rect.removeInsets(this._getAttr("borderInsets"));
        const showHeader = this.getName() !== undefined;
        let y = 0;
        let h = 0;
        if (showHeader) {
            y += this._calculatedHeaderBarHeight;
            h += this._calculatedHeaderBarHeight;
        }
        if (this.isEnableTabStrip()) {
            if (this.getTabLocation() === "top") {
                this._tabHeaderRect = new Rect_1.Rect(rect.x, rect.y + y, rect.width, this._calculatedTabBarHeight);
            }
            else {
                this._tabHeaderRect = new Rect_1.Rect(rect.x, rect.y + rect.height - this._calculatedTabBarHeight, rect.width, this._calculatedTabBarHeight);
            }
            h += this._calculatedTabBarHeight;
            if (this.getTabLocation() === "top") {
                y += this._calculatedTabBarHeight;
            }
        }
        this._contentRect = new Rect_1.Rect(rect.x, rect.y + y, rect.width, rect.height - h);
        for (let i = 0; i < this._children.length; i++) {
            const child = this._children[i];
            child._layout(this._contentRect, metrics);
            child._setVisible(i === this.getSelected());
        }
    }
    /** @internal */
    _delete() {
        this._parent._removeChild(this);
    }
    /** @internal */
    _remove(node) {
        const removedIndex = this._removeChild(node);
        this._model._tidy();
        (0, Utils_1.adjustSelectedIndex)(this, removedIndex);
    }
    /** @internal */
    drop(dragNode, location, index, select) {
        const dockLocation = location;
        if (this === dragNode) {
            // tabset drop into itself
            return; // dock back to itself
        }
        let dragParent = dragNode.getParent();
        let fromIndex = 0;
        if (dragParent !== undefined) {
            fromIndex = dragParent._removeChild(dragNode);
            // if selected node in border is being docked into tabset then deselect border tabs
            if (dragParent instanceof BorderNode_1.BorderNode && dragParent.getSelected() === fromIndex) {
                dragParent._setSelected(-1);
            }
            else {
                (0, Utils_1.adjustSelectedIndex)(dragParent, fromIndex);
            }
        }
        // if dropping a tab back to same tabset and moving to forward position then reduce insertion index
        if (dragNode.getType() === TabNode_1.TabNode.TYPE && dragParent === this && fromIndex < index && index > 0) {
            index--;
        }
        // simple_bundled dock to existing tabset
        if (dockLocation === DockLocation_1.DockLocation.CENTER) {
            let insertPos = index;
            if (insertPos === -1) {
                insertPos = this._children.length;
            }
            if (dragNode.getType() === TabNode_1.TabNode.TYPE) {
                this._addChild(dragNode, insertPos);
                if (select || (select !== false && this.isAutoSelectTab())) {
                    this._setSelected(insertPos);
                }
                // console.log("added child at : " + insertPos);
            }
            else {
                for (let i = 0; i < dragNode.getChildren().length; i++) {
                    const child = dragNode.getChildren()[i];
                    this._addChild(child, insertPos);
                    // console.log("added child at : " + insertPos);
                    insertPos++;
                }
                if (this.getSelected() === -1 && this._children.length > 0) {
                    this._setSelected(0);
                }
            }
            this._model._setActiveTabset(this);
        }
        else {
            let tabSet;
            if (dragNode instanceof TabNode_1.TabNode) {
                // create new tabset parent
                // console.log("create a new tabset");
                const callback = this._model._getOnCreateTabSet();
                tabSet = new TabSetNode(this._model, callback ? callback(dragNode) : {});
                tabSet._addChild(dragNode);
                // console.log("added child at end");
                dragParent = tabSet;
            }
            else {
                tabSet = dragNode;
            }
            const parentRow = this._parent;
            const pos = parentRow.getChildren().indexOf(this);
            if (parentRow.getOrientation() === dockLocation._orientation) {
                tabSet._setWeight(this.getWeight() / 2);
                this._setWeight(this.getWeight() / 2);
                // console.log("added child 50% size at: " +  pos + dockLocation.indexPlus);
                parentRow._addChild(tabSet, pos + dockLocation._indexPlus);
            }
            else {
                // create a new row to host the new tabset (it will go in the opposite direction)
                // console.log("create a new row");
                const newRow = new RowNode_1.RowNode(this._model, {});
                newRow._setWeight(this.getWeight());
                newRow._addChild(this);
                this._setWeight(50);
                tabSet._setWeight(50);
                // console.log("added child 50% size at: " +  dockLocation.indexPlus);
                newRow._addChild(tabSet, dockLocation._indexPlus);
                parentRow._removeChild(this);
                parentRow._addChild(newRow, pos);
            }
            this._model._setActiveTabset(tabSet);
        }
        this._model._tidy();
    }
    toJson() {
        const json = {};
        TabSetNode._attributeDefinitions.toJson(json, this._attributes);
        json.children = this._children.map((child) => child.toJson());
        if (this.isActive()) {
            json.active = true;
        }
        if (this.isMaximized()) {
            json.maximized = true;
        }
        return json;
    }
    /** @internal */
    _updateAttrs(json) {
        TabSetNode._attributeDefinitions.update(json, this._attributes);
    }
    /** @internal */
    _getAttributeDefinitions() {
        return TabSetNode._attributeDefinitions;
    }
    /** @internal */
    _getPrefSize(orientation) {
        let prefSize = this.getWidth();
        if (orientation === Orientation_1.Orientation.VERT) {
            prefSize = this.getHeight();
        }
        return prefSize;
    }
    /** @internal */
    static getAttributeDefinitions() {
        return TabSetNode._attributeDefinitions;
    }
}
exports.TabSetNode = TabSetNode;
TabSetNode.TYPE = "tabset";
/** @internal */
TabSetNode._attributeDefinitions = TabSetNode._createAttributeDefinitions();
//# sourceMappingURL=TabSetNode.js.map

/***/ }),

/***/ 9571:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   N9: function() { return /* binding */ Q; }
/* harmony export */ });
/* unused harmony exports Bounce, Flip, Icons, Slide, Zoom, collapseToast, cssTransition, toast, useToast, useToastContainer */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6540);
/* harmony import */ var clsx__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4164);
'use client';
const c=e=>"number"==typeof e&&!isNaN(e),d=e=>"string"==typeof e,u=e=>"function"==typeof e,p=e=>d(e)||u(e)?e:null,m=e=>(0,react__WEBPACK_IMPORTED_MODULE_0__.isValidElement)(e)||d(e)||u(e)||c(e);function f(e,t,n){void 0===n&&(n=300);const{scrollHeight:o,style:s}=e;requestAnimationFrame(()=>{s.minHeight="initial",s.height=o+"px",s.transition=`all ${n}ms`,requestAnimationFrame(()=>{s.height="0",s.padding="0",s.margin="0",setTimeout(t,n)})})}function g(t){let{enter:a,exit:r,appendPosition:i=!1,collapse:l=!0,collapseDuration:c=300}=t;return function(t){let{children:d,position:u,preventExitTransition:p,done:m,nodeRef:g,isIn:y,playToast:v}=t;const h=i?`${a}--${u}`:a,T=i?`${r}--${u}`:r,E=(0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(0);return (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{const e=g.current,t=h.split(" "),n=o=>{o.target===g.current&&(v(),e.removeEventListener("animationend",n),e.removeEventListener("animationcancel",n),0===E.current&&"animationcancel"!==o.type&&e.classList.remove(...t))};e.classList.add(...t),e.addEventListener("animationend",n),e.addEventListener("animationcancel",n)},[]),(0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{const e=g.current,t=()=>{e.removeEventListener("animationend",t),l?f(e,m,c):m()};y||(p?t():(E.current=1,e.className+=` ${T}`,e.addEventListener("animationend",t)))},[y]),react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment,null,d)}}function y(e,t){return null!=e?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const v=new Map;let h=[];const T=new Set,E=e=>T.forEach(t=>t(e)),b=()=>v.size>0;function I(e,t){var n;if(t)return!(null==(n=v.get(t))||!n.isToastActive(e));let o=!1;return v.forEach(t=>{t.isToastActive(e)&&(o=!0)}),o}function _(e,t){m(e)&&(b()||h.push({content:e,options:t}),v.forEach(n=>{n.buildToast(e,t)}))}function C(e,t){v.forEach(n=>{null!=t&&null!=t&&t.containerId?(null==t?void 0:t.containerId)===n.id&&n.toggle(e,null==t?void 0:t.id):n.toggle(e,null==t?void 0:t.id)})}function L(e){const{subscribe:o,getSnapshot:s,setProps:i}=(0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(function(e){const n=e.containerId||1;return{subscribe(o){const s=function(e,n,o){let s=1,r=0,i=[],l=[],f=[],g=n;const v=new Map,h=new Set,T=()=>{f=Array.from(v.values()),h.forEach(e=>e())},E=e=>{l=null==e?[]:l.filter(t=>t!==e),T()},b=e=>{const{toastId:n,onOpen:s,updateId:a,children:r}=e.props,i=null==a;e.staleId&&v.delete(e.staleId),v.set(n,e),l=[...l,e.props.toastId].filter(t=>t!==e.staleId),T(),o(y(e,i?"added":"updated")),i&&u(s)&&s((0,react__WEBPACK_IMPORTED_MODULE_0__.isValidElement)(r)&&r.props)};return{id:e,props:g,observe:e=>(h.add(e),()=>h.delete(e)),toggle:(e,t)=>{v.forEach(n=>{null!=t&&t!==n.props.toastId||u(n.toggle)&&n.toggle(e)})},removeToast:E,toasts:v,clearQueue:()=>{r-=i.length,i=[]},buildToast:(n,l)=>{if((t=>{let{containerId:n,toastId:o,updateId:s}=t;const a=n?n!==e:1!==e,r=v.has(o)&&null==s;return a||r})(l))return;const{toastId:f,updateId:h,data:I,staleId:_,delay:C}=l,L=()=>{E(f)},N=null==h;N&&r++;const $={...g,style:g.toastStyle,key:s++,...Object.fromEntries(Object.entries(l).filter(e=>{let[t,n]=e;return null!=n})),toastId:f,updateId:h,data:I,closeToast:L,isIn:!1,className:p(l.className||g.toastClassName),bodyClassName:p(l.bodyClassName||g.bodyClassName),progressClassName:p(l.progressClassName||g.progressClassName),autoClose:!l.isLoading&&(w=l.autoClose,k=g.autoClose,!1===w||c(w)&&w>0?w:k),deleteToast(){const e=v.get(f),{onClose:n,children:s}=e.props;u(n)&&n((0,react__WEBPACK_IMPORTED_MODULE_0__.isValidElement)(s)&&s.props),o(y(e,"removed")),v.delete(f),r--,r<0&&(r=0),i.length>0?b(i.shift()):T()}};var w,k;$.closeButton=g.closeButton,!1===l.closeButton||m(l.closeButton)?$.closeButton=l.closeButton:!0===l.closeButton&&($.closeButton=!m(g.closeButton)||g.closeButton);let P=n;(0,react__WEBPACK_IMPORTED_MODULE_0__.isValidElement)(n)&&!d(n.type)?P=(0,react__WEBPACK_IMPORTED_MODULE_0__.cloneElement)(n,{closeToast:L,toastProps:$,data:I}):u(n)&&(P=n({closeToast:L,toastProps:$,data:I}));const M={content:P,props:$,staleId:_};g.limit&&g.limit>0&&r>g.limit&&N?i.push(M):c(C)?setTimeout(()=>{b(M)},C):b(M)},setProps(e){g=e},setToggle:(e,t)=>{v.get(e).toggle=t},isToastActive:e=>l.some(t=>t===e),getSnapshot:()=>g.newestOnTop?f.reverse():f}}(n,e,E);v.set(n,s);const r=s.observe(o);return h.forEach(e=>_(e.content,e.options)),h=[],()=>{r(),v.delete(n)}},setProps(e){var t;null==(t=v.get(n))||t.setProps(e)},getSnapshot(){var e;return null==(e=v.get(n))?void 0:e.getSnapshot()}}}(e)).current;i(e);const l=(0,react__WEBPACK_IMPORTED_MODULE_0__.useSyncExternalStore)(o,s,s);return{getToastToRender:function(e){if(!l)return[];const t=new Map;return l.forEach(e=>{const{position:n}=e.props;t.has(n)||t.set(n,[]),t.get(n).push(e)}),Array.from(t,t=>e(t[0],t[1]))},isToastActive:I,count:null==l?void 0:l.length}}function N(e){const[t,o]=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(!1),[a,r]=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(!1),l=(0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null),c=(0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:d,pauseOnHover:u,closeToast:p,onClick:m,closeOnClick:f}=e;var g,y;function h(){o(!0)}function T(){o(!1)}function E(n){const o=l.current;c.canDrag&&o&&(c.didMove=!0,t&&T(),c.delta="x"===e.draggableDirection?n.clientX-c.start:n.clientY-c.start,c.start!==n.clientX&&(c.canCloseOnClick=!1),o.style.transform=`translate3d(${"x"===e.draggableDirection?`${c.delta}px, var(--y)`:`0, calc(${c.delta}px + var(--y))`},0)`,o.style.opacity=""+(1-Math.abs(c.delta/c.removalDistance)))}function b(){document.removeEventListener("pointermove",E),document.removeEventListener("pointerup",b);const t=l.current;if(c.canDrag&&c.didMove&&t){if(c.canDrag=!1,Math.abs(c.delta)>c.removalDistance)return r(!0),e.closeToast(),void e.collapseAll();t.style.transition="transform 0.2s, opacity 0.2s",t.style.removeProperty("transform"),t.style.removeProperty("opacity")}}null==(y=v.get((g={id:e.toastId,containerId:e.containerId,fn:o}).containerId||1))||y.setToggle(g.id,g.fn),(0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||T(),window.addEventListener("focus",h),window.addEventListener("blur",T),()=>{window.removeEventListener("focus",h),window.removeEventListener("blur",T)}},[e.pauseOnFocusLoss]);const I={onPointerDown:function(t){if(!0===e.draggable||e.draggable===t.pointerType){c.didMove=!1,document.addEventListener("pointermove",E),document.addEventListener("pointerup",b);const n=l.current;c.canCloseOnClick=!0,c.canDrag=!0,n.style.transition="none","x"===e.draggableDirection?(c.start=t.clientX,c.removalDistance=n.offsetWidth*(e.draggablePercent/100)):(c.start=t.clientY,c.removalDistance=n.offsetHeight*(80===e.draggablePercent?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(t){const{top:n,bottom:o,left:s,right:a}=l.current.getBoundingClientRect();"touchend"!==t.nativeEvent.type&&e.pauseOnHover&&t.clientX>=s&&t.clientX<=a&&t.clientY>=n&&t.clientY<=o?T():h()}};return d&&u&&(I.onMouseEnter=T,e.stacked||(I.onMouseLeave=h)),f&&(I.onClick=e=>{m&&m(e),c.canCloseOnClick&&p()}),{playToast:h,pauseToast:T,isRunning:t,preventExitTransition:a,toastRef:l,eventHandlers:I}}function $(t){let{delay:n,isRunning:o,closeToast:s,type:a="default",hide:r,className:i,style:c,controlledProgress:d,progress:p,rtl:m,isIn:f,theme:g}=t;const y=r||d&&0===p,v={...c,animationDuration:`${n}ms`,animationPlayState:o?"running":"paused"};d&&(v.transform=`scaleX(${p})`);const h=(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)("Toastify__progress-bar",d?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${g}`,`Toastify__progress-bar--${a}`,{"Toastify__progress-bar--rtl":m}),T=u(i)?i({rtl:m,type:a,defaultClassName:h}):(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)(h,i),E={[d&&p>=1?"onTransitionEnd":"onAnimationEnd"]:d&&p<1?null:()=>{f&&s()}};return react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":y},react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${g} Toastify__progress-bar--${a}`}),react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{role:"progressbar","aria-hidden":y?"true":"false","aria-label":"notification timer",className:T,style:v,...E}))}let w=1;const k=()=>""+w++;function P(e){return e&&(d(e.toastId)||c(e.toastId))?e.toastId:k()}function M(e,t){return _(e,t),t.toastId}function x(e,t){return{...t,type:t&&t.type||e,toastId:P(t)}}function A(e){return(t,n)=>M(t,x(e,n))}function B(e,t){return M(e,x("default",t))}B.loading=(e,t)=>M(e,x("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),B.promise=function(e,t,n){let o,{pending:s,error:a,success:r}=t;s&&(o=d(s)?B.loading(s,n):B.loading(s.render,{...n,...s}));const i={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},l=(e,t,s)=>{if(null==t)return void B.dismiss(o);const a={type:e,...i,...n,data:s},r=d(t)?{render:t}:t;return o?B.update(o,{...a,...r}):B(r.render,{...a,...r}),s},c=u(e)?e():e;return c.then(e=>l("success",r,e)).catch(e=>l("error",a,e)),c},B.success=A("success"),B.info=A("info"),B.error=A("error"),B.warning=A("warning"),B.warn=B.warning,B.dark=(e,t)=>M(e,x("default",{theme:"dark",...t})),B.dismiss=function(e){!function(e){var t;if(b()){if(null==e||d(t=e)||c(t))v.forEach(t=>{t.removeToast(e)});else if(e&&("containerId"in e||"id"in e)){const t=v.get(e.containerId);t?t.removeToast(e.id):v.forEach(t=>{t.removeToast(e.id)})}}else h=h.filter(t=>null!=e&&t.options.toastId!==e)}(e)},B.clearWaitingQueue=function(e){void 0===e&&(e={}),v.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},B.isActive=I,B.update=function(e,t){void 0===t&&(t={});const n=((e,t)=>{var n;let{containerId:o}=t;return null==(n=v.get(o||1))?void 0:n.toasts.get(e)})(e,t);if(n){const{props:o,content:s}=n,a={delay:100,...o,...t,toastId:t.toastId||e,updateId:k()};a.toastId!==e&&(a.staleId=e);const r=a.render||s;delete a.render,M(r,a)}},B.done=e=>{B.update(e,{progress:1})},B.onChange=function(e){return T.add(e),()=>{T.delete(e)}},B.play=e=>C(!0,e),B.pause=e=>C(!1,e);const O="undefined"!=typeof window?react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect:react__WEBPACK_IMPORTED_MODULE_0__.useEffect,D=t=>{let{theme:n,type:o,isLoading:s,...a}=t;return react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:"colored"===n?"currentColor":`var(--toastify-icon-color-${o})`,...a})},z={info:function(t){return react__WEBPACK_IMPORTED_MODULE_0__.createElement(D,{...t},react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(t){return react__WEBPACK_IMPORTED_MODULE_0__.createElement(D,{...t},react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(t){return react__WEBPACK_IMPORTED_MODULE_0__.createElement(D,{...t},react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(t){return react__WEBPACK_IMPORTED_MODULE_0__.createElement(D,{...t},react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{className:"Toastify__spinner"})}},R=n=>{const{isRunning:o,preventExitTransition:s,toastRef:r,eventHandlers:i,playToast:c}=N(n),{closeButton:d,children:p,autoClose:m,onClick:f,type:g,hideProgressBar:y,closeToast:v,transition:h,position:T,className:E,style:b,bodyClassName:I,bodyStyle:_,progressClassName:C,progressStyle:L,updateId:w,role:k,progress:P,rtl:M,toastId:x,deleteToast:A,isIn:B,isLoading:O,closeOnClick:D,theme:R}=n,S=(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)("Toastify__toast",`Toastify__toast-theme--${R}`,`Toastify__toast--${g}`,{"Toastify__toast--rtl":M},{"Toastify__toast--close-on-click":D}),H=u(E)?E({rtl:M,position:T,type:g,defaultClassName:S}):(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)(S,E),F=function(e){let{theme:n,type:o,isLoading:s,icon:r}=e,i=null;const l={theme:n,type:o};return!1===r||(u(r)?i=r({...l,isLoading:s}):(0,react__WEBPACK_IMPORTED_MODULE_0__.isValidElement)(r)?i=(0,react__WEBPACK_IMPORTED_MODULE_0__.cloneElement)(r,l):s?i=z.spinner():(e=>e in z)(o)&&(i=z[o](l))),i}(n),X=!!P||!m,Y={closeToast:v,type:g,theme:R};let q=null;return!1===d||(q=u(d)?d(Y):(0,react__WEBPACK_IMPORTED_MODULE_0__.isValidElement)(d)?(0,react__WEBPACK_IMPORTED_MODULE_0__.cloneElement)(d,Y):function(t){let{closeToast:n,theme:o,ariaLabel:s="close"}=t;return react__WEBPACK_IMPORTED_MODULE_0__.createElement("button",{className:`Toastify__close-button Toastify__close-button--${o}`,type:"button",onClick:e=>{e.stopPropagation(),n(e)},"aria-label":s},react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(Y)),react__WEBPACK_IMPORTED_MODULE_0__.createElement(h,{isIn:B,done:A,position:T,preventExitTransition:s,nodeRef:r,playToast:c},react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{id:x,onClick:f,"data-in":B,className:H,...i,style:b,ref:r},react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{...B&&{role:k},className:u(I)?I({type:g}):(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)("Toastify__toast-body",I),style:_},null!=F&&react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{className:(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!O})},F),react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",null,p)),q,react__WEBPACK_IMPORTED_MODULE_0__.createElement($,{...w&&!X?{key:`pb-${w}`}:{},rtl:M,theme:R,delay:m,isRunning:o,isIn:B,closeToast:v,hide:y,type:g,style:L,className:C,controlledProgress:X,progress:P||0})))},S=function(e,t){return void 0===t&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},H=g(S("bounce",!0)),F=g(S("slide",!0)),X=g(S("zoom")),Y=g(S("flip")),q={position:"top-right",transition:H,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function Q(t){let o={...q,...t};const s=t.stacked,[a,r]=(0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(!0),c=(0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null),{getToastToRender:d,isToastActive:m,count:f}=L(o),{className:g,style:y,rtl:v,containerId:h}=o;function T(e){const t=(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)("Toastify__toast-container",`Toastify__toast-container--${e}`,{"Toastify__toast-container--rtl":v});return u(g)?g({position:e,rtl:v,defaultClassName:t}):(0,clsx__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)(t,p(g))}function E(){s&&(r(!0),B.play())}return O(()=>{if(s){var e;const t=c.current.querySelectorAll('[data-in="true"]'),n=12,s=null==(e=o.position)?void 0:e.includes("top");let r=0,i=0;Array.from(t).reverse().forEach((e,t)=>{const o=e;o.classList.add("Toastify__toast--stacked"),t>0&&(o.dataset.collapsed=`${a}`),o.dataset.pos||(o.dataset.pos=s?"top":"bot");const l=r*(a?.2:1)+(a?0:n*t);o.style.setProperty("--y",`${s?l:-1*l}px`),o.style.setProperty("--g",`${n}`),o.style.setProperty("--s",""+(1-(a?i:0))),r+=o.offsetHeight,i+=.025})}},[a,f,s]),react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{ref:c,className:"Toastify",id:h,onMouseEnter:()=>{s&&(r(!1),B.pause())},onMouseLeave:E},d((t,n)=>{const o=n.length?{...y}:{...y,pointerEvents:"none"};return react__WEBPACK_IMPORTED_MODULE_0__.createElement("div",{className:T(t),style:o,key:`container-${t}`},n.map(t=>{let{content:n,props:o}=t;return react__WEBPACK_IMPORTED_MODULE_0__.createElement(R,{...o,stacked:s,collapseAll:E,isIn:m(o.toastId,o.containerId),style:o.style,key:`toast-${o.key}`},n)}))}))}
//# sourceMappingURL=react-toastify.esm.mjs.map


/***/ }),

/***/ 9888:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(8493);
} else // removed by dead control flow
{}


/***/ }),

/***/ 9919:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.showPopup = void 0;
const React = __webpack_require__(6540);
const DragDrop_1 = __webpack_require__(883);
const Types_1 = __webpack_require__(6643);
const TabButtonStamp_1 = __webpack_require__(2486);
/** @internal */
function showPopup(triggerElement, items, onSelect, layout, iconFactory, titleFactory) {
    var _a;
    const layoutDiv = layout.getRootDiv();
    const classNameMapper = layout.getClassName;
    const currentDocument = triggerElement.ownerDocument;
    const triggerRect = triggerElement.getBoundingClientRect();
    const layoutRect = (_a = layoutDiv === null || layoutDiv === void 0 ? void 0 : layoutDiv.getBoundingClientRect()) !== null && _a !== void 0 ? _a : new DOMRect(0, 0, 100, 100);
    const elm = currentDocument.createElement("div");
    elm.className = classNameMapper(Types_1.CLASSES.FLEXLAYOUT__POPUP_MENU_CONTAINER);
    if (triggerRect.left < layoutRect.left + layoutRect.width / 2) {
        elm.style.left = triggerRect.left - layoutRect.left + "px";
    }
    else {
        elm.style.right = layoutRect.right - triggerRect.right + "px";
    }
    if (triggerRect.top < layoutRect.top + layoutRect.height / 2) {
        elm.style.top = triggerRect.top - layoutRect.top + "px";
    }
    else {
        elm.style.bottom = layoutRect.bottom - triggerRect.bottom + "px";
    }
    DragDrop_1.DragDrop.instance.addGlass(() => onHide());
    DragDrop_1.DragDrop.instance.setGlassCursorOverride("default");
    if (layoutDiv) {
        layoutDiv.appendChild(elm);
    }
    const onHide = () => {
        layout.hidePortal();
        DragDrop_1.DragDrop.instance.hideGlass();
        if (layoutDiv) {
            layoutDiv.removeChild(elm);
        }
        elm.removeEventListener("mousedown", onElementMouseDown);
        currentDocument.removeEventListener("mousedown", onDocMouseDown);
    };
    const onElementMouseDown = (event) => {
        event.stopPropagation();
    };
    const onDocMouseDown = (_event) => {
        onHide();
    };
    elm.addEventListener("mousedown", onElementMouseDown);
    currentDocument.addEventListener("mousedown", onDocMouseDown);
    layout.showPortal(React.createElement(PopupMenu, { currentDocument: currentDocument, onSelect: onSelect, onHide: onHide, items: items, classNameMapper: classNameMapper, layout: layout, iconFactory: iconFactory, titleFactory: titleFactory }), elm);
}
exports.showPopup = showPopup;
/** @internal */
const PopupMenu = (props) => {
    const { items, onHide, onSelect, classNameMapper, layout, iconFactory, titleFactory } = props;
    const onItemClick = (item, event) => {
        onSelect(item);
        onHide();
        event.stopPropagation();
    };
    const itemElements = items.map((item, i) => (React.createElement("div", { key: item.index, className: classNameMapper(Types_1.CLASSES.FLEXLAYOUT__POPUP_MENU_ITEM), "data-layout-path": "/popup-menu/tb" + i, onClick: (event) => onItemClick(item, event), title: item.node.getHelpText() }, item.node.getModel().isLegacyOverflowMenu() ?
        item.node._getNameForOverflowMenu() :
        React.createElement(TabButtonStamp_1.TabButtonStamp, { node: item.node, layout: layout, iconFactory: iconFactory, titleFactory: titleFactory }))));
    return (React.createElement("div", { className: classNameMapper(Types_1.CLASSES.FLEXLAYOUT__POPUP_MENU), "data-layout-path": "/popup-menu" }, itemElements));
};
//# sourceMappingURL=PopupMenu.js.map

/***/ }),

/***/ 9982:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(7463);
} else // removed by dead control flow
{}


/***/ })

}]);
//# sourceMappingURL=vendors.f82ad68d.js.map